resultMap


@Data 
public class Student { 
    private int id; 
    private String name; 
    private Teacher teacher; 
}

 @Data 
public class Teacher {
     private int id; 
    private String name; 
} 
一:查询所有学生的信息以及对应的老师信息
二:如何将老师的信息封装到Student类teacher属性中?
三:
  一:使用association,按照查询嵌套处理    
<association property="被查询的类(A)的属性",column="对应表的列",javaType="被查询的类(A)属性对应类(B)",select="查询对应的类(B)结果"/><?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.nbg.dao.StudentMapper">    <resultMap id="S_T" type="student"> <id column="id" property="id"/> <id column="name" property="name"/> <association column="tid" property="teacher" javaType="Teacher" select="getTeacher"/> </resultMap> <select id="getTeacher" resultType="Teacher"> select * from teacher where id = #{tid}; </select> <select id="getStudentList" resultMap="S_T">   select * from student </select> </mapper> 方式二: <resultMap id="S_T_2" type="student"> <id column="sid" property="id"/> <id column="sname" property="name"/> <association property="teacher" javaType="Teacher"> <result property="name" column="tname"/> </association> </resultMap> <select id="getStudentList2" resultMap="S_T_2"> select s.id sid,s.name sname,t.name tname from student s,teacher t where s.tid = t.id; </select>
<!--
查询结果如下:Teacher的id都为0?不是id = 1 || id = 2?
Student(id=1, name=张三, teacher=Teacher(id=0, name=毛))
Student(id=2, name=李四, teacher=Teacher(id=0, name=毛))
Student(id=3, name=王五, teacher=Teacher(id=0, name=毛))
Student(id=4, name=赵四, teacher=Teacher(id=0, name=周))
-->
@Data
public class Student {
    private int id;
    private String name;
    private int tid;
}

@Data
public class Teacher {
    private int id;
    private String name;
    private List<Student> students;
}

   二:使用collection

    方式一:      

<resultMap id="T_S" type="Teacher">
    <id column="tid" property="id"/>
    <id column="tname" property="name"/>
    <collection property="students" ofType="Student">
       <result column="sid" property="id"/>
        <result column="sname" property="name"/>
        <result column="stid" property="tid"/>
    </collection>
</resultMap>
<select id="getTeacher" resultMap="T_S">
   select t.id tid, t.name tname, s.tid stid, s.id sid , s.name sname from teacher t,student s
   where s.tid = t.id
   and t.id = #{id};
</select>

 

    方式二:

<select id="getTeacher2" resultMap="T_S_2">
  select * from teacher where id = #{id};
</select>

<resultMap id="T_S_2" type="Teacher">
    <id property="id" column="id"/>
    <id property="name" column="name"/>
    <collection property="students" javaType="ArrayList" ofType="Student" select="S_S" column="id"/>
</resultMap>

<select id="S_S" resultType="Student" parameterType="int">
    select * from student where tid = #{tid};
</select>

 

posted @ 2020-12-02 22:13  nbg  阅读(73)  评论(0编辑  收藏  举报