mybatis多表查詢(resultMap 聯合查詢)
阿新 • • 發佈:2021-01-12
mybatis多表聯合查詢(單一物件)
只需要一個StudentMapper(一條SQL聯合查詢)就夠
- Student為學生類,每個學生有自己的老師編號(tid),Teacher老師類,編號id
- 現在通過s.tid=t.id將兩張表聯合
- association的寫法和N+1有區別
<?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.wit.mapper.StudentMapper">
<resultMap type="Student" id="stuMap1">
<id column="sid" property="id"/>
<result column="sname" property="name"/>
<result column="age" property ="age"/>
<result column="tid" property="tid"/>
<association property="teacher" javaType="Teacher" >
<id column="tid" property="id"/>
<result column="tname" property="name"/>
</ association>
</resultMap>
<select id="selAll1" resultMap="stuMap1">
select s.id sid,s.name sname,age age,t.id
tid,t.name tname FROM student s left outer join teacher t on s.tid=t.id
</select>
</mapper>
mybatis多表聯合查詢(物件集合)
cn.wit.pojo
Student
- id
- name
- age
- tid
Teacher
- id
- name
- List<?>
StudentMapper.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.wit.mapper.TeacherMapper">
<resultMap type="teacher" id="mymap">
<id column="id" property="id"/>
<result column="name" property="name"/>
<collection property="list" ofType="student">
<id column="sid" property="id"/>
<result column="sname" property="name"/>
<result column="age" property="age"/>
<result column="tid" property="tid"/>
</collection>
</resultMap>
<select id="selAll" resultMap="mymap">
select t.id id,t.name name,
s.id sid,s.name sname,age,tid FROM teacher t left outer join student s on s.tid=t.id
</select>
</mapper>