目录
多对一
需求
查询所有学生信息以及对应的老师信息。
要查询学生实体,但学生实体里面还包含一个老师实体

按照查询嵌套
这种方法的思路是2个SQL,一个查学生,一个查老师,然后拼接起来
<mapper namespace="lt.dao.StudentMapper">
<select id="getStudent" resultMap="StudentTeacher">
select * from student
</select>
<resultMap id="StudentTeacher" type="Student">
<result property="id" column="id"/>
<result property="name" column="name"/>
<!--复杂的属性,我们需要单独处理。对象就用association,集合就用collection-->
<association property="teacher" column="tid" javaType="Teacher" select="getTeacher"/>
</resultMap>
<select id="getTeacher" resultType="Teacher">
select * from teacher where id = #{id}
</select>
</mapper>
方法执行时只查Student里的东西即可

按照结果嵌套
这种方法的思路是一条SQL把需要的东西都查出来了,然后通过拼接结果集,返回一个完整的Student实体
<!--按照结果嵌套处理-->
<select id="getStudent2" resultMap="StudentTeacher2">
select s.id sid,s.name sname,t.name tname from student s,teacher t where s.tid = t.id;
</select>
<resultMap id="StudentTeacher2" type="Student">
<result property="id" column="sid"/>
<result property="name" column="sname"/>
<association property="teacher" javaType="Teacher">
<result property="name" column="tname"/>
</association>
</resultMap>
新建一个测试方法

两种方法结果一样

一对多
按结果集嵌套

按查询嵌套
![]()
JavaType&ofType
1.JavaType 用来指定实体类中属性的类型
2.ofType用来指定泛型中的约束类型
本文详细介绍了MyBatis框架下多对一和一对多关联查询的实现方式,包括按照查询嵌套和按照结果嵌套的方法。通过具体示例,展示了如何使用association和collection标签进行复杂属性的处理。

233

被折叠的 条评论
为什么被折叠?



