欢迎光临散文网 会员登陆 & 注册

Oracle,Mybatis嵌套查询,对映射,外键,主键,反射的理解,关联元素【诗书画唱】

2021-03-12 09:23 作者:诗书画唱  | 我要投稿

概括:

association关联元素

嵌套查询


个人对映射,外键,主键,反射的理解:集合声明都是在属于“主”的关键的部分的xml文件,其实可以联想到外键的设置,比如

type表的id要设置为主键,就是为了使用外键时,确认主从的关系,有主键的就是属于

“主”的关系,就是“一”的关系,在这个“主从关系”中有主键的表的话就是主表。

其实“映射"和”反射“的话都是打印内容的时候就是会存在一些的主从关系的。通过哦的思考,实践等等,我发现其实把”一“对”多“等的关系,理解成”主从关系“就很好理解了。

建议命名id时有区分地命名,该统一命名的部分就统一命名,不然容易搞混。

建议命名id时有区分地命名,该统一命名的部分就统一命名,不然容易搞混。
个人对映射,外键,主键,反射的理解:集合声明都是在属于“主”的关键的部分的xml文件,其实可以联想到外键的设置,比如 

type表的id要设置为主键,就是为了使用外键时,确认主从的关系,有主键的就是属于 

“主”的关系,就是“一”的关系,在这个“主从关系”中有主键的表的话就是主表。 

其实“映射"和”反射“的话都是打印内容的时候就是会存在一些的主从关系的。通过哦的思考,实践等等,我发现其实把”一“对”多“等的关系,理解成”主从关系“就很好理解了。





个人的理解的笔记 START

一般是在作为“一”的对象中,声明出

 作为“多”的对象这个类。pt就是ptype的缩写,如果不熟的话就是

 命名具体一些,如果很熟了就简短有意义的命名。



个人对映射,外键,主键,反射的理解:集合声明都是在属于“主”的关键的部分的xml文件,其实可以联想到外键的设置,比如

type表的id要设置为主键,就是为了使用外键时,确认主从的关系,有主键的就是属于

“主”的关系,就是“一”的关系,在这个“主从关系”中有主键的表的话就是主表。

其实“映射"和”反射“的话都是打印内容的时候就是会存在一些的主从关系的。通过哦的思考,实践等等,我发现其实把”一“对”多“等的关系,理解成”主从关系“就很好理解了。

个人对映射,外键,主键,反射的理解:集合声明都是在属于“主”的关键的部分的xml文件,其实可以联想到外键的设置,比如

type表的id要设置为主键,就是为了使用外键时,确认主从的关系,有主键的就是属于

“主”的关系,就是“一”的关系,在这个“主从关系”中有主键的表的话就是主表。

其实“映射"和”反射“的话都是打印内容的时候就是会存在一些的主从关系的。通过哦的思考,实践等等,我发现其实把”一“对”多“等的关系,理解成”主从关系“就很好理解了。


个人的理解的笔记 END





个人的注意事项的记录 START


个人对“多对多”的理解:就是2个对象都具有本身对应多个对方的情况,是2个相互作用的

一对多。



id和result都映射一个单独列的值到简单数据类型(字符串,整型,双精度浮点数,日期等)的单独属性或字段。这两者之间的唯一不同是id表示操作对象实例时用到的标识属性。用来提高程序的运行速度,特别是缓存和嵌入结果映射(也就是联合映射)。包含如下的属性:

association元素:

关联元素处理“有一个”类型的关系。例如:学生只可以选择一个专业班级。需要通过配置文件告诉MyBatis如何加载关联。上面的例子就是一个典型的嵌套查询的配置。







个人的注意事项的记录 END



关于日志包 START



关于日志包 END

讲义 START

sqlserver,mysql,oracle:关系型数据库

数据库的关系类型:一对一,一对多(多对一),多对多

身份证号和人:通过身份证号只能找到唯一的一个人,每个人只有唯一的一个身份证号

一对多:班级和学生,一个班级中可以有很多的学生,每个学生只能在唯一的一个班级中

多对多:科目和学生:一个科目可以同时被许多学生选中,一个学生同时选多个科目

商品和订单

角色和账号


Person表:id,cardid(身份证号),在表中通过一个字段就可以搞定一对一的关系

Student表:id,name,sex,cid

Cls表:id,name

在表中通过外键引用关系就可以搞定一对多的关系

Subject表:id,sname,desc

Stuinfo表 :id,name,sex

科目和学生关系表:id,subid,stuid,score

在表中通过第三个关系表就可以搞定多对多的关系


商品和商品类型:每个商品对应唯一的商品类型,每个商品类型中可以有很多的商品(多对一)


在mybatis框架中实现一对多的关系

讲义 END

示例 START





 --drop table Product                

create table Product(

    id number primary key,

    pname varchar2(30) not null,

   price  number(10,2),

  ptype  number

);


--drop sequence seq_Product

create sequence seq_Product

start with 1       --起始值是1

increment by 1     --增长的值   

maxvalue 999999999 --序列号的最大值

minvalue 1         --序列号的最小值

nocycle            --是否循环

cache 10;          --预存



insert into Product values(seq_Product.nextval,'黑笔',1.5,1);

insert into Product values(seq_Product.nextval,'红书',2.0,2);

insert into Product values(seq_Product.nextval,'挂面',3.0,3);


--select * from Product





 --drop table Protype                

create table Protype(

    id number primary key,

    tname varchar2(30) not null

 

);


--drop sequence seq_Protype

create sequence seq_Protype

start with 1       --起始值是1

increment by 1     --增长的值   

maxvalue 999999999 --序列号的最大值

minvalue 1         --序列号的最小值

nocycle            --是否循环

cache 10;          --预存



insert into Protype values(seq_Protype.nextval,'笔');

insert into Protype values(seq_Protype.nextval,'书');

insert into Protype values(seq_Protype.nextval,'面');


--select * from Protype

package com.SSHC.bean;

//一对多中的一:

public class Product {

    private Integer id;

    private String pname;

    private Double price;

    private Integer ptype;

    //pt就是关系属性(数据库没pt这一列):

    private Protype pt;

public Integer getId() {

return id;

}

public void setId(Integer id) {

this.id = id;

}

public String getPname() {

return pname;

}

public void setPname(String pname) {

this.pname = pname;

}

public Double getPrice() {

return price;

}

public void setPrice(Double price) {

this.price = price;

}

public Integer getPtype() {

return ptype;

}

public void setPtype(Integer ptype) {

this.ptype = ptype;

}

public Protype getPt() {

return pt;

}

public void setPt(Protype pt) {

this.pt = pt;

}

}


package com.SSHC.bean;


import java.util.List;


public class Protype {

    private Integer id;

    private String tname;

    

    //反向关联属性

    private List<Product>plist;

public Integer getId() {

return id;

}

public void setId(Integer id) {

this.id = id;

}

public String getTname() {

return tname;

}

public void setTname(String tname) {

this.tname = tname;

}

public List<Product> getPlist() {

return plist;

}

public void setPlist(List<Product> plist) {

this.plist = plist;

}

}

package com.SSHC.bean;


public class Userinfo {

    private Integer id;

    private String act;

    private String pwd;

    private String birth;

public Integer getId() {

return id;

}

public void setId(Integer id) {

this.id = id;

}

public String getAct() {

return act;

}

public void setAct(String act) {

this.act = act;

}

public String getPwd() {

return pwd;

}

public void setPwd(String pwd) {

this.pwd = pwd;

}

public String getBirth() {

return birth;

}

public void setBirth(String birth) {

this.birth = birth;

}

}



<?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPE mapper

    PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"  

    "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<!-- namespace就是空间名,它必须在整个项目中都是唯一的 -->

<mapper namespace="com.SSHC.dao.ProductDao">

    <!-- id必须是唯一的 -->

    <resultMap type="Product" id="rmProduct">

        <id property="id" column="ID" />

    <result property="pname" column="PNAME"/>

    <result property="price" column="PRICE"/>

    <result property="ptype" column="PTYPE"/>

    <!-- 配置一对多的关系映射 -->

    <!--

       property就是指的Product对应的唯一的商品类型对象

       column就是指从Product表中查询的商品类型id取自Product表的哪个列

       select就是指需要执行的商品类型的查询语句

    -->

    <association property="pt" column="PTYPE"

        select="com.SSHC.dao.ProtypeDao.selectById" >

        <id property="id" column="ID" />

        <result property="tname" column="TNAME" />

    </association>

    </resultMap>

    <!-- public List<Product>selectAll() -->

    <select id="selectAll" resultMap="rmProduct">

        select * from product

    </select>

    <!-- public List<Product>selectByTid(Integer tid) -->

    <select id="selectByTid" resultMap="rmProduct">

        select * from product where ptype = #{tid}

    </select>

</mapper>


<?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPE mapper

    PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"  

    "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<!-- namespace就是空间名,它必须在整个项目中都是唯一的 -->

<mapper namespace="com.SSHC.dao.ProtypeDao">

    <!-- id必须是唯一的 -->

    <resultMap type="Protype" id="rmProtype">

        <id property="id" column="ID" />

    <result property="tname" column="TNAME"/>

    <!--

    property指的就是Protype属性中的关系属性名 

    javaType指的就是plist的类型是一个ArrayList

    column指的就是商品类型id取自Protype表中的哪个列

    ofType指的就是plist中存放的对象类型

    select指的就是需要执行的查询语句

    -->

    <collection property="plist" javaType="ArrayList" 

    column="ID"

        ofType="Product" 

        select="com.SSHC.dao.ProductDao.selectByTid">

    </collection>

    </resultMap>

    <!-- public Protype selectById(Integer id) -->

    <select id="selectById" resultMap="rmProtype">

        select * from protype where id = #{id}

    </select>

    <!-- public List<Protype>selectAll() -->

    <select id="selectAll" resultMap="rmProtype">

        select * from protype

    </select>

</mapper>

<?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPE mapper

    PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"  

    "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<!-- namespa"src/com/SSHC/bean/UserinfoSqlMap.xml"ce就是空间名,它必须在整个项目中都是唯一的 -->

<mapper namespace="com.SSHC.dao.UserinfoDao">

    <!-- id必须是唯一的 -->

    <!-- 创建一个List<Userinfo>集合,变量名叫rmUserinfo -->

    <resultMap type="Userinfo" id="rmUserinfo">

        <!-- userinfo表的主键是id -->

        <!-- property指的是Userinfo类的属性名,

             column指的是userinfo表的列名 -->

        <!-- u.setId(rs.getInt("ID")) -->

        <id property="id" column="ID" />

        <!-- u.setAct(rs.getInt("ACT")) -->

    <result property="act" column="ACT"/>

    <result property="pwd" column="PWD"/>

    <result property="birth" column="BIRTH"/>

    </resultMap>

    <!-- 可以重复的使用 -->

    <sql id="whereCls">

        where id = #{id}

    </sql>

    <!-- public List<Userinfo>selectAll() -->

    <select id="selectAll" resultMap="rmUserinfo">

        select * from userinfo

    </select>

    

    <!-- public Userinfo selectById(Integer id) -->

    <!-- mybatis框架中,占位符?使用#{}来代替 -->

    <select id="selectById" resultMap="rmUserinfo">

        select * from userinfo <include refid="whereCls"></include>

    </select>

    

    <!-- public Integer add(Userinfo u) -->

    <!-- 因为参数的类型是Userinfo,所以占位符中的字符串就必须是对应的属性名

         (属性名区分大小写) -->

    <insert id="add" parameterType="Userinfo">

        insert into userinfo 

values(seq_userinfo.nextval,

#{act},#{pwd},to_date(#{birth},'yyyy-mm-dd'))

    </insert>

    <!-- mysql的新增:keyProperty表示自动增长的列的列名叫什么 -->

    <insert id="addMySQL" parameterType="Userinfo"

        useGeneratedKeys="true" keyProperty="id">

        insert into userinfo (act,pwd,birth) 

        values(#{act},#{pwd},#{birth})

    </insert>

    

    <!-- public Integer update(Userinfo u) -->

    <update id="update" parameterType="Userinfo">

        update userinfo set act = #{act},pwd = #{pwd},birth = to_date(#{birth},'yyyy-mm-dd')

        <include refid="whereCls"></include>

    </update>

    <!-- public Integer deleteById(Integer id) -->

    <delete id="deleteById">

        delete from userinfo <include refid="whereCls"></include>

    </delete>

</mapper>



/** CTRL+F:

 * 在使用Mybatis框架前要用的JDBC的代码,使用Mybatis框架后

就不必使用


下面的内容是通过for的嵌套的遍历打印出

2个表的内容

 * */



package ZSGC;




import java.io.IOException;

import java.io.Reader;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.util.ArrayList;

import java.util.List;

import java.util.Scanner;


import org.apache.ibatis.io.Resources;

import org.apache.ibatis.session.SqlSession;

import org.apache.ibatis.session.SqlSessionFactory;

import org.apache.ibatis.session.SqlSessionFactoryBuilder;


import com.SSHC.bean.Product;

import com.SSHC.bean.Protype;

import com.SSHC.bean.Userinfo;



public class Test {


public static void main(String[] args) {

// TODO Auto-generated method stub

/** 在使用Mybatis框架前要用的JDBC的代码,使用Mybatis框架后

就不必使用 START*/


//        String drivername = "oracle.jdbc.driver.OracleDriver";

//        //oracle数据库的默认端口号1521

//        //连接的数据库名字是orcl数据库

//        String url = "jdbc:oracle:thin:@localhost:1521:orcl";

//        String username = "j190802";

//        String pwd = "orcl";

//        

//        Connection conn = null;

//        PreparedStatement pstm = null;

//        ResultSet rs = null;

//        

//        try {

//        Class.forName(drivername);

// conn = DriverManager.getConnection(url,username,pwd);

// pstm = conn.prepareStatement("select * from userinfo where id = ?");

// pstm.setInt(1, 8);

// rs = pstm.executeQuery();

// List<Userinfo>rmUserinfo = new ArrayList<Userinfo>();

// while(rs.next()) {

// Userinfo u = new Userinfo();

// //ID是userinfo表的主键

// u.setId(rs.getInt("ID"));

// u.setAct(rs.getString("ACT"));

// System.out.println(rs.getString("ACT"));

// u.setPwd(rs.getString("PWD"));

// u.setBirth(rs.getString("BIRTH"));

// rmUserinfo.add(u);

// }

//

// String sql = "insert into userinfo values(?,?,?,to_date(?,'yyyy-mm-dd'))";

// pstm = conn.prepareStatement(sql);

// Userinfo u = new Userinfo();

// u.setId(11);

// u.setAct("haha");

// u.setPwd("09876");

// u.setBirth("2000-7-3");

// pstm.setInt(1, u.getId());

// pstm.setString(2, u.getAct());

// pstm.setString(3, u.getPwd());

// pstm.setString(4, u.getBirth());

// int count = pstm.executeUpdate();

// System.out.println(count);

// } catch (Exception e) {

// // TODO Auto-generated catch block

// e.printStackTrace();

// } finally {

// try {

// if(rs != null) {

// rs.close();

// }

// if(pstm != null) {

// pstm.close();

// }

// if(conn != null) {

// conn.close();

// }

// } catch(Exception e) {

// e.printStackTrace();

// }

// }

/** 在使用Mybatis框架前要用的JDBC的代码,使用Mybatis框架后

就不必使用 END*/

//为了获取主配置文件的路径而去声明一个path的变量:

String path = "mybatis.xml";

//读取mybatis.xml中的配置信息,就是读取四大连接字符串的内容:

Reader config;

try {

config = Resources.getResourceAsReader(path);

SqlSessionFactory factory = 

new SqlSessionFactoryBuilder().build(config);

//数据库的操作对象session(这个是自己命名的):

SqlSession session = factory.openSession();

//调用selectAll

//执行路径就是映射文件的namespace属性+'.'+id


while(true){


System.out.print("请选择操作:1.查询"

+ "Userinfo表的所有内容 "

+ ",2.查询ProductDao表的所有内容,"

+ "\n 3.嵌套查询,"

+ "4.UserinfoDao的id查询,"

+ "\n"

+ "5.Oracle中的UserinfoDao表的运用序列的新增,"


+ "\n 6.MySQL中的UserinfoDao表的运用自增的新增 ,"

+ "\n 7.UserinfoDao表的修改,"

+ "\n8.根据ID删除UserinfoDao表的内容");

   Scanner input = new Scanner(System.in);

   int num = input.nextInt();

   System.out.println(num);

   String exePath = null;


if(num==1){


exePath = "com.SSHC.dao.UserinfoDao.selectAll";

List<Userinfo>list = session.selectList(exePath);

for(Userinfo u : list) {

System.out.println(u.getId()+" "+u.getAct()+" "+u.getBirth()

+" "+u.getPwd());

}



}


if(num==2){


exePath = "com.SSHC.dao.ProductDao.selectAll";

List<Product>lt = session.selectList(exePath);

for(Product p : lt) {

System.out.println(p.getPname());

Integer ptype = p.getPtype();

//还要进行一次查询才可以将商品类型中文名称查询出来

// Protype pt = session

// .selectOne("com.SSHC.dao.ProtypeDao.selectById",ptype);

// System.out.println(pt.getTname());

System.out.println(p.getPt().getTname());

}


}

if(num==3){

/**下面的内容是通过for的嵌套的遍历打印出

2个表的内容 START */


exePath = "com.SSHC.dao.ProtypeDao.selectAll";

List<Protype>ls = session.selectList(exePath);

for(Protype pt : ls){

System.out.println(pt.getTname());

List<Product>plist = pt.getPlist();

for(Product p : plist) {

System.out.println(p.getPname());

}

}

/**下面的内容是通过for的嵌套的遍历打印出

2个表的内容 END */

}


if(num==4){

exePath = "com.SSHC.dao.UserinfoDao.selectById";

Userinfo u = session.selectOne(exePath,1);

System.out.println(u.getAct());

}

if(num==5){

exePath = "com.SSHC.dao.UserinfoDao.add";

Userinfo u = new Userinfo();

u.setAct("诗书画唱");

u.setPwd("999");

u.setBirth("2009-9-20");

Integer count = session.insert(exePath,u);

//新增修改和删除一定记得提交事务

session.commit();

System.out.println(count);

}

if(num==6){

exePath = "com.SSHC.dao.UserinfoDao.addMySQL";

Userinfo u = new Userinfo();

u.setAct("诗书画唱");

u.setPwd("666");

u.setBirth("1999-7-7");

Integer count = session.insert(exePath,u);

//新增修改和删除一定记得提交事务

session.commit();

System.out.println(count);

}

if(num==7){

Userinfo u = new Userinfo();

u.setId(11);

u.setAct("测试账号");

u.setPwd("555555");

u.setBirth("1998-11-29");

exePath = "com.SSHC.dao.UserinfoDao.update";

Integer count = session.update(exePath,u);

//新增修改和删除一定记得提交事务

session.commit();

System.out.println(count);

}

if(num==8){

exePath = "com.SSHC.dao.UserinfoDao.deleteById";

Integer count = session.delete(exePath,8);

//新增修改和删除一定记得提交事务

session.commit();

System.out.println(count);

}


}} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}


}

oracle_drivername=oracle.jdbc.driver.OracleDriver

oracle_url=jdbc:oracle:thin:@localhost:1521:orcl

oracle_username=X

oracle_password=sshcPwd


mysql_drivername=com.mysql.jdbc.Driver

mysql_url=jdbc:mysql://localhost:3306/j190802?useUnicode=true&amp;characterEncoding=GBK2312

mysql_username=root

mysql_password=1


sqlserver_drivername=com.microsoft.sqlserver.jdbc.SQLServerDriver

sqlserver_url=jdbc:sqlserver://localhost:1433;databaseName=cervs

sqlserver_username=sa

sqlserver_password=



log4j.rootLogger=DEBUG,Console

#Console

log4j.appender.Console=org.apache.log4j.ConsoleAppender

log4j.appender.Console.layout=org.apache.log4j.PatternLayout

log4j.appender.Console.layout.ConversionPattern=%d[%t] %-5p [%c] - %m%n

log4j.logger.java.sql.ResultSet=INFO

log4j.logger.org.apache=INFO

log4j.logger.java.sql.Connection=DEBUG

log4j.logger.java.sql.Statement=DEBUG

log4j.logger.java.sql.PreparedStatement=DEBUG

<?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"  

    "http://mybatis.org/dtd/mybatis-3-config.dtd">

<configuration>  

    <!-- 读取指定的properties文件中的内容 -->

    <properties resource="db.properties"></properties> 

    <!-- 给类取一个简短的别名 -->

    <typeAliases>

        <package name="com.SSHC.bean"/>

    </typeAliases>

    <environments default="oracleConf">                 

        <!-- oracle配置 --> 

        <environment id="oracleConf">  

            <transactionManager type="JDBC"> 

                <property name="closeConnection" value="false"/>

            </transactionManager> 

            <!-- 配置数据源 -->       

            <dataSource type="POOLED">

                <property name="driver" value="${oracle_drivername}"/>   

                <property name="url" value="${oracle_url}"/> 

                <property name="username" value="${oracle_username}"/> 

                <property name="password" value="${oracle_password}"/>  

            </dataSource>    

        </environment>

        <!-- mysql配置 -->

        <environment id="mysqlConf">

            <!-- 事务配置 -->

            <transactionManager type="JDBC"> 

                <property name="closeConnection" value="false"/>

            </transactionManager> 

            <!-- 配置数据源 -->       

            <dataSource type="POOLED">

                <property name="driver" value="${mysql_drivername}"/>   

                <property name="url" value="${mysql_url}"/> 

                <property name="username" value="${mysql_username}"/> 

                <property name="password" value="${mysql_password}"/>  

            </dataSource>

        </environment>

    </environments> 

    <!-- 实体映射文件集合 --> 

    <mappers>

        <!-- 告诉mybatis框架,映射文件放在什么地方 -->

        <mapper resource="com/SSHC/bean/UserinfoSqlMap.xml"/>

        <mapper resource="com/SSHC/bean/ProductSqlMap.xml"/>

        <mapper resource="com/SSHC/bean/ProtypeSqlMap.xml"/>

    </mappers>

</configuration>




示例 END


Oracle,Mybatis嵌套查询,对映射,外键,主键,反射的理解,关联元素【诗书画唱】的评论 (共 条)

分享到微博请遵守国家法律