使用ResultMap进行一对多的复杂数据查询
在学生与老师这样的多对一的关系,并且学生实体类中存储的是一个老师的对象
//学生实体
@Data
public class Student {
private int id;
private String name;
private Teacher teacher;//数据库中记录的此字段为tid
}
//教师实体
@Data
public class Teacher {
private int id;
private String name;
}
此时查询需要使用resultMap
**方式一:**按照查询嵌套处理
<!--结果集使用resultMap -->
<select id="getStudent" resultMap="studentMap">
select * from student
</select>
<!--resultMap对应学生查询的结果集 类型为学生实体类型 -->
<resultMap id="studentMap" type="student">
<result property="id" column="id"/>
<result property="name" column="name"/>
<!--处理Teacher复杂属性 property对应类中属性名称 column对应数据库中字段名称 javaType类型对应Teacher类 select对应查询教师方法 -->
<association property="teacher" column="tid" javaType="Teacher" select="selectTeacherById"/>
</resultMap>
<!-- 查询教师方法 -->
<select id="selectTeacherById" resultType="teacher">
select * from teacher where id = #{id}
</select>
**方式二:**按照返回结果处理
<select id="getStudent2" resultMap="StudentTeacher">
select s.id sid , s.name sname ,t.name tname
from student s ,teacher t
where s.tid = t.id
</select>
<resultMap id="StudentTeacher" type="student">
<result property="id" column="sid"/>
<result property="name" column="sname"/>
<association property="teacher" javaType="Teacher">
<result property="name" column="tname"/>
</association>
</resultMap>
图解:
在老师与学生这样的一对多的关系,并且老师实体类中存储的是一个学生对象的list集合
使用resultMap进行处理
//教师实体类
@Data
public class Teacher {
private int id;
private String name;
private List<Student> students;
}
//学生实体类
@Data
public class Student {
private int id;
private String name;
private int tid;
}
查询处理
**方式一:**使用结果集进行处理
Teacher getTeacherStudentById(@Param("tid") int id);
<select id="getTeacherStudentById" resultMap="TeacherStudent">
select t.id tid,t.name tname,s.name sname,s.id sid
from teacher t, student s
where t.id = s.tid and t.id = #{tid}
</select>
<!--
复杂属性处理: collection处理集合 association:处理对象
javaType:获取指定属性类型
ofType:获取集合中的泛型类型
-->
<resultMap id="TeacherStudent" type="Teacher">
<result property="id" column="tid"/>
<result property="name" column="tname"/>
<collection property="students" ofType="Student">
<result property="name" column="sname"/>
<result property="id" column="sid"/>
<result property="tid" column="tid"/>
</collection>
</resultMap>
**方式二:**使用查询嵌套进行处理
<select id="getTeacherById" resultMap="getTS">
select * from teacher where id = #{tid}
</select>
<select id="getStudent" resultType="student">
SELECT * FROM student where tid = #{tid}
</select>
<resultMap id="getTS" type="teacher">
<!-- column中的值为教师表中的教师ID 注意这里写的并不是起的别名tid 也不是学生数据库表中的教师tid -->
<collection property="students" javaType="ArrayList" ofType="Student" select="getStudent" column="id"/>
</resultMap>