Mybatis入门笔记(三)
——2018年11月14日
Mybatis多表关联查询:
现在有三张表需要关联查询:分别为学生表(Student) 老师表(Teacher)
妻子表(Wife)
下面我们对上面三张表进行关联查询
需求:要在查询一个老师信息的时候就查询出老师相关联的所有学生和自己的妻子。
回顾以往用JDBC时查询时需要将老师的信息全部查询出啦,然后通过老师的id查询学生的所有信息,和妻子的信息。那样在数据层处理的东西就比较大,但是如果用mybatis的关联查询,也会带来一定的缓存污染,这时候就需要用到mybatis的懒加载机制,缓存机制将在下一篇文章中详细介绍:
①.先封装实体类:有Student,Teacher,Wife
②..xml的配置
<mapper namespace="org.robert.mapper.TeacherMapper">
<!--使用resultMap映射实体类和字段之间的一一对应的关系-->
<resultMap id="teacherMap" type="Teacher">
<id column="t_id" property="id"></id>
<result column="t_name" property="name"></result>
<result column="t_salary" property="salary"></result>
<!--
myBatis一对一关联查询总结
property:对象属性的名称
javaType:对象属性的类型
column:所对应的外键字段名称
select:使用另一个查询封装的结果
-->
<association property="wife" javaType="Wife">
<id column="w_id" property="id"></id>
<result column="w_name" property="name"></result>
</association>
<!--
多表查询
ofType:集合中元素的对象类型
-->
<collection property="stu" ofType="Student">
<id column="s_id" property="id"></id>
<result column="s_name" property="name"></result>
<result column="s_sex" property="sex"></result>
<result column="s_age" property="age"></result>
<result column="s_teacher" property="teacher"></result>
</collection>
</resultMap>
<!--多表查询-->
<select id="get" resultType="Teacher">
select * from teacher where id=#{id}
</select>
<!--多表查询,查询一个老师对应的学生和妻子-->
<select id="getall" resultMap="teacherMap">
select t.id t_id,t.name t_name,t.salary t_salary,
s.id s_id,s.name s_name,s.sex s_sex,s.age s_age,s.teacher s_teacher,
w.id w_id,w.name w_name
from teacher t
join student s
on s.teacher=t.id
join wife w
on w.id=t.wife
where t.id=#{id}
</select>
测试类:
Log4j打印结果: