MyBatis对数据库进行一对多,多对多,一对一的配置操作

工具类

//获取SqlSession
public class DbUtil {
    public static SqlSession getSqlSession(){
        try {
            Reader reader = Resources.getResourceAsReader("configuration.xml");
            SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
            SqlSessionFactory factory = builder.build(reader);
            SqlSession  session = factory.openSession();
            return session;
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }
}

1.一对多

1.表:只要有主外键就都可以看成是一对多的关系

DROP TABLE IF EXISTS `emp`;
CREATE TABLE `emp` (
  `EMPNO` int(11) NOT NULL,
  `ENAME` varchar(10) default NULL,
  `JOB` varchar(9) default NULL,
  `MGR` int(11) default NULL,
  `HIREDATE` date default NULL,
  `SAL` float default NULL,
  `COMM` float default NULL,
  `DEPTNO` int(11) default NULL,
  PRIMARY KEY  (`EMPNO`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
DROP TABLE IF EXISTS `dept`;
CREATE TABLE `dept` (
  `DEPTNO` int(11) NOT NULL,
  `DNAME` varchar(14) default NULL,
  `LOC` varchar(13) default NULL,
  PRIMARY KEY  (`DEPTNO`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

2.实体类:

去设置相关对应对象

3.Mapper接口

public interface DeptMapper {
    public List<Dept> queryAllDept();
    public Dept querySingleDept(Integer deptno);
    public Integer addDept(Dept dept);
    public Integer updateDept(Dept dept);
    public boolean deleteDept(Integer deptno);
}
public interface EmpMapper {
    public List<Emp> queryAllEmp();
    public Emp querySingleEmp(Integer empno);
    public boolean updateEmp(Emp emp);
    public List<Emp> queryEmpByDeptno(Integer deptno1);
}

4.xml配置

<?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">

<mapper namespace="com.hc.mapper.DeptMapper">
    <resultMap id="DeptMap" type="Dept">
        <id column="deptno" property="deptno"></id>

        <!-- 一对多 配置
        collection select :查出一个Dept对象后 使用deptno列作为条件查询对应的Emp列表,赋值给empList属性
        fetchType:是否立即加载关联对象  一端建议使用lazy
        -->
        <collection property="empList" column="deptno" javaType="java.util.List"
        select="com.hc.mapper.EmpMapper.queryEmpByDeptno" fetchType="lazy"></collection>

    </resultMap>


    <select id="queryAllDept" resultMap="DeptMap">
        select * from dept
    </select>

    <select id="querySingleDept" resultMap="DeptMap"  parameterType="INTEGER">
        select * from dept where deptno = #{deptno}
    </select>

    <insert id="addDept"  parameterType="Dept">
        insert into dept(dname,loc) values(#{dname},#{loc})
    </insert>

    <update id="updateDept" parameterType="Dept">
        update dept set dname=#{dname},loc = #{loc} where deptno = #{deptno}
    </update>

    <delete id="deleteDept" parameterType="INTEGER">
        delete from dept where deptno = #{deptno}
    </delete>
    
</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">
<!-- 来配置mapper包下的DeptMapper接口中的sql操作 -->
<mapper namespace="com.hc.mapper.EmpMapper">
    <!--当出现对象的属性 与 表的列不匹配时 必须进行 resultMap配置
    id 这个map配置的名字
    type: 针对哪个实体类做的配置
    <id/>:这是在配置主键
    <result/>:这是在配置普通列
        property : 类的属性名  column 列名
    -->
    <resultMap id="EmpMap" type="Emp">
        <id property="empno" column="empno" javaType="java.lang.Integer" jdbcType="INTEGER"></id>
        <result property="empname" column="ename" javaType="java.lang.String" jdbcType="VARCHAR"></result>
        <result property="empjob" column="job" javaType="java.lang.String" jdbcType="VARCHAR"></result>
        <result property="hiredate" column="hiredate" javaType="java.util.Date" jdbcType="DATE"></result>
        <result property="deptno1" column="deptno1"></result>
        <!-- 多对一配置
        association  select :使用哪一个查询 以deptno为条件查询出一个Dept对象赋值给dept属性
        fetchType : 执行本身查询时是否会立即执行关联查询 多端建议使用 eager
        -->
        <association property="dept" column="deptno1"  javaType="Dept" jdbcType="INTEGER"
         select="com.hc.mapper.DeptMapper.querySingleDept" fetchType="eager"></association>

    </resultMap>

    <select id="queryAllEmp"  resultMap="EmpMap">
        select e.*,d.* from emp e,dept d where e.deptno = d.deptno and empno=#{empno}
    </select>

    <!-- select中 就使用上面配置的 ResultMap -->
<!--    <select id="queryAllEmp"  resultMap="EmpMap">-->
<!--        select * from emp-->
<!--    </select>-->

    <select id="querySingleEmp" resultMap="EmpMap">
        select * from emp where empno = #{empno}
    </select>

    <update id="updateEmp" parameterType="Emp">
        update emp set ename=#{ename},job =#{job},hiredate=#{hiredate} where empno = #{empno}
    </update>

    <select id="queryEmpByDeptno" parameterType="INTEGER" resultMap="EmpMap">
        select * from emp where deptno = #{deptno1}
    </select>
</mapper>

5.测试

public class Test1 {
    public static void main(String[] args) {
        //1.一对多
        SqlSession session = DbUtil.getSqlSession();
        EmpMapper empMapper = session.getMapper(EmpMapper.class);
        DeptMapper deptMapper = session.getMapper(DeptMapper.class);

        List<Dept> deptList = deptMapper.queryAllDept();
        for(Dept d:deptList){
            System.out.println(d.getDname());
            System.out.println(d.getEmpList());
            for (Emp e : d.getEmpList()){
                System.out.println(e);
            }
        }
        session.close();
    }
}

6.运行结果

 

2.多对多

1.表:两表之间要有关联表

CREATE TABLE stu -- 学生表
(
stuid INT PRIMARY KEY,
stuname VARCHAR(50) NOT NULL,
stusex VARCHAR(50) NOT NULL
);

CREATE TABLE teacher -- 老师表
(
teaid INT PRIMARY KEY,
teaname VARCHAR(50) NOT NULL,
teasex VARCHAR(50) NOT NULL
);

CREATE TABLE s_t -- 学生老师关联表
(
stid INT  PRIMARY KEY,
stuid INT REFERENCES stu(stuid),
teaid INT REFERENCES teacher(teaid) 
);

2.实体类:

去设置相关对应对象

3.Mapper接口

public interface StuMapper {
    public List<Stu> queryAll();
    public Stu querySingle(Integer stuid);

    //通过teaid查询Stu集合
    public List<Stu> queryByTeaid(Integer teaid);

}
public interface TeacherMapper {
    public List<Teacher> queryAll();
    public Teacher querySingle(Integer teaid);
    //以stuid为条件查询所有Teacher
    public List<Teacher> queryByStuid(Integer stuid);
}

4.xml配置

<?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">

<mapper namespace="com.hc.mapper.StuMapper">
    <resultMap id="StuMap" type="Stu">
        <id property="stuid" column="stuid"></id>

        <!--多对多 查询出一个Stu对象后 以stuid为条件查询对应的Teacher集合 -->
        <collection property="teacherList" column="stuid" javaType="java.util.List"
        select="com.hc.mapper.TeacherMapper.queryByStuid"  fetchType="lazy"></collection>
    </resultMap>
    
    <select id="queryAll" resultMap="StuMap">
        select * from stu
    </select>

    <select id="querySingle" resultMap="StuMap"  parameterType="INTEGER">
        select * from stu where stuid = #{stuid}
    </select>

    <select id="queryByTeaid" resultMap="StuMap" parameterType="INTEGER">
        SELECT * FROM stu s,s_t WHERE s_t.stuid = s.stuid AND teaid=#{teaid}
    </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">

<mapper namespace="com.hc.mapper.TeacherMapper">
    <resultMap id="TeacherMap" type="Teacher">
        <id property="teaid" column="teaid"></id>

        <!--多对多 查询出一个Teacher对象后 以teaid为条件查询对应的Stu集合 -->
        <collection property="stuList" column="teaid" javaType="java.util.List"
         select= "com.hc.mapper.StuMapper.queryByTeaid" fetchType="lazy"></collection>

    </resultMap>
    
    <select id="queryAll" resultMap="TeacherMap">
        select * from teacher
    </select>

    <select id="querySingle" resultMap="TeacherMap"  parameterType="INTEGER">
        select * from teacher where teaid = #{teaid}
    </select>

   <select id="queryByStuid" resultMap="TeacherMap" parameterType="INTEGER">
        SELECT * FROM teacher t,s_t WHERE s_t.teaid = t.teaid AND stuid=#{stuid}
   </select>

</mapper>

5.测试

public class Test2 {
    public static void main(String[] args) {
        /*
        2多对多  学生 老师
        表设计:两表之间还要有一个中间的关联表 关联表当中就包含两表的外键 但关联表本身不作为实体
        类设计:学生中包含老师集合   老师中包含学生集合
        配置:两边配置都使用 collection
         */
        SqlSession session = DbUtil.getSqlSession();
        StuMapper stuMapper = session.getMapper(StuMapper.class);
        TeacherMapper teacherMapper = session.getMapper(TeacherMapper.class);

        Stu stu = stuMapper.querySingle(1);
        System.out.println(stu);
        System.out.println(stu.getTeacherList());

        List<Stu> stuList = stuMapper.queryAll();
        for(Stu s : stuList){
            System.out.println(s);
            System.out.println(s.getTeacherList());
        }

        session.close();
    }
}

6.运行结果

 

3.一对一

1.表:表中外键还需要加上唯一键约束

CREATE TABLE person   -- 人员表
(
pid INT PRIMARY KEY AUTO_INCREMENT,
pname VARCHAR(20),
psex VARCHAR(10),
page INT  
);

CREATE TABLE idcard  -- 证件表
(
cid INT PRIMARY KEY AUTO_INCREMENT,
cardNumber VARCHAR(18),
pid INT UNIQUE   -- 唯一键
);

2.实体类:

去设置相关对应对象

3.Mapper接口

public interface IdcardMapper {
    public List<Idcard> queryAll();
    public Idcard querySingle(Integer cid);

    //通过pid查询唯一Idcard对象
    public Idcard queryByPid(Integer pid);
}
public interface PersonMapper {
    public List<Person> queryAll();
    public Person querySingle(Integer pid);
}

4.xml配置

<?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">

<mapper namespace="com.hc.mapper.PersonMapper">
    <resultMap id="PersonMap" type="Person">
        <id property="pid" column="pid"></id>

        <!-- 查询到一个Person 使用其pid作为条件 去查询对应的一个Idcard -->
        <association property="idcard" column="pid" javaType="Idcard"
         select="com.hc.mapper.IdcardMapper.queryByPid"  fetchType="eager"></association>
    </resultMap>


    <select id="queryAll" resultMap="PersonMap">
        select * from person
    </select>

    <select id="querySingle" resultMap="PersonMap"  parameterType="INTEGER">
        select * from person where pid = #{pid}
    </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">

<mapper namespace="com.hc.mapper.IdcardMapper">
    <resultMap id="IdcardMap" type="Idcard">
        <id property="cid" column="cid"></id>
        <result property="pid" column="pid"></result>

        <!--查到一个Idcard ,依据其中pid 去查询对应Person对象 -->
        <association property="person" column="pid" javaType="Person"
         select="com.hc.mapper.PersonMapper.querySingle"  fetchType="eager"></association>
    </resultMap>
    
    <select id="queryAll" resultMap="IdcardMap">
        select * from idcard
    </select>

    <select id="querySingle" resultMap="IdcardMap"  parameterType="INTEGER">
        select * from idcard where cid = #{cid}
    </select>

    <select id="queryByPid" resultMap="IdcardMap" parameterType="INTEGER">
        select * from idcard where pid = #{pid}
    </select>

</mapper>

5.测试

public class Test3 {
    public static void main(String[] args) {
        //一对一
        SqlSession session = DbUtil.getSqlSession();
        PersonMapper personMapper = session.getMapper(PersonMapper.class);
        IdcardMapper idcardMapper = session.getMapper(IdcardMapper.class);

        Person person = personMapper.querySingle(1);
        System.out.println(person);
        System.out.println(person.getIdcard());

        Idcard idcard = idcardMapper.querySingle(101);
        System.out.println(idcard);
        System.out.println(idcard.getPerson());
        
        session.close();
    }
}

6.运行结果

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值