复杂查询结果集处理,使用ResultMap
-
多对一的处理,直接上代码,主要是理解ResultMap的精髓................
POJO
@Data public class Student { private int id; private String name; private Teacher teacher; } @Data public class Teacher { private int id; private String name; private List<Student> studentList; }
DAO
public interface StudentMapper { //查询出学生和老师的对应关系 public List<Student> getStudentList(); }
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="dao.StudentMapper">
<select id="getStudentList" resultMap="map1">
select s.id sid, s.name sname, t.name tname, t.id tid from student s, teacher t where s.tid=t.id;
</select>
<resultMap id="map1" type="pojo.Student">
<result property="id" column="sid"></result>
<result property="name" column="sname"></result>
<association property="teacher" javaType="pojo.Teacher">
<result property="name" column="tname"></result>
<result property="id" column="tid"></result>
</association>
</resultMap>c
</mapper>
-
一对多的处理
POJO同上
Dao
public interface TeacherMapper { //一对多 //获取指定老师及老师下所有的学生信息 public Teacher getTeachers(int id); }
<mapper namespace="dao.TeacherMapper">
<select id="getTeachers" resultMap="map1">
select t.id tid, t.name tname, s.id sid, s.name sname from teacher t, student s where s.tid=t.id and t.id=#{id}
</select>
<resultMap id="map1" type="Teacher">
<result property="id" column="tid"></result>
<result property="name" column="tname"></result>
<collection property="studentList" ofType="pojo.Student">
<result property="id" column="sid"></result>
<result property="name" column="sname"></result>
</collection>
</resultMap>
</mapper>