07_关于联表的处理

时间:2019-08-20
本文章向大家介绍07_关于联表的处理,主要包括07_关于联表的处理使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

1、多对一的处理

  a) 数据库表的设计

 学生表student与老师表teacher

  b) 实体类

  c)编写映射文件student.mapper.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="cn.sxt.entity.student.mapper">
    <!-- 对于多对一处理有两种方式1、按结果嵌套处理2、按查询嵌套处理 -->
    <select id="getStudents" resultMap="StudentTeacher">
        select s.id sid,s.name sname,s.tid stid,t.id tid,t.name tname from student s,teacher t where s.tid = t.id
    </select>
    <resultMap type="Student" id="StudentTeacher">重点在这一块
        <id column="sid" property="id"/>
        <result column="sname" property="name"/>
        <association property="teacher" javaType="Teacher">
            <id column="tid" property="id"/>
            <result column="tname" property="name"/>
        </association>
    </resultMap>
</mapper>

    第二种方式:按查询嵌套处理,有两种写法(这种方式相当于做了两次查询) 

one

 这种方式student.mapper.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="cn.sxt.entity.student.mapper">
    <!-- 对于多对一处理有两种方式1、按结果嵌套处理2、按查询嵌套处理 
    <select id="getStudents" resultMap="StudentTeacher">
        select s.id sid,s.name sname,s.tid stid,t.id tid,t.name tname from student s,teacher t where s.tid = t.id
    </select>
    <resultMap type="Student" id="StudentTeacher">
        <id column="sid" property="id"/>
        <result column="sname" property="name"/>
        <association property="teacher" javaType="Teacher">
            <id column="tid" property="id"/>
            <result column="tname" property="name"/>
        </association>
    </resultMap>
    -->
    <select id="getStudents" resultMap="StudentTeacher">
        select * from student
    </select>
    <resultMap type="Student" id="StudentTeacher">
        <association property="teacher" column="tid" javaType="Teacher" select="cn.sxt.entity.teacher.mapper.getTeacher"></association>
    </resultMap>
</mapper>

 teacher.mapper.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="cn.sxt.entity.teacher.mapper">
    <select id="getTeacher" resultType="Teacher">
        select * from teacher where id=#{id}
    </select>
</mapper>

 另外还需要在mybatis.cfg.xml中添加配置

two

然后在mybatis.cfg.xml配置文件里面只写一个

原文地址:https://www.cnblogs.com/djlindex/p/11386306.html