多对一的查询处理
1.按照查询嵌套处理。将多表的数据分别查出来然后用resultMap对应起来
(复杂属性的字段使用association(对应对象)或者collection(对应集合)来映射)
<?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.gsy.dao.StudentMapper">
<resultMap id="getS" type="com.gsy.pojo.Student">
<association property="tid" column="tid" javaType="com.gsy.pojo.Teacher" select="getTea"/>
</resultMap>
<select id="getStudent" resultMap="getS">
SELECT * from student
</select>
<select id="getTea" resultType="com.gsy.pojo.Teacher">
SELECT * from teacher where id=#{tid}
</select>
</mapper>
2.按照结果嵌套处理。将数据直接查询出来
<select id="getS" resultMap="TaS">
SELECT s.id sid,s.name sname,t.id tid,t.name tname
from student s,teacher t
where s.tid=t.id
</select>
<resultMap id="TaS" type="com.gsy.pojo.Student">
<result property="id" column="sid"/>
<result property="name" column="sname"/>
<association property="tid" javaType="com.gsy.pojo.Teacher">
<result property="name" column="tname"/>
<result property="id" column="tid"/>
</association>
</resultMap>
一对多的子查询处理
一对多的子查询使用collection来进行处理
<select id="getTeacher2" resultMap="TS2">
select * from teacher where id = #{tid};
</select>
<resultMap id="TS2" type="com.gsy.pojo.Teacher">
<collection property="students" javaType="ArrayList" ofType="com.gsy.pojo.Student" select="getStuByTid" column="id"/>
</resultMap>
<select id="getStuByTid" resultType="com.gsy.pojo.Student">
select * from student where tid = #{tid};
</select>