Mybatis的级联查询
resultMap 元素有很多子元素和一个值得深入探讨的结构。 下面是resultMap 元素的概念视图
结果映射(resultMap)
constructor - 用于在实例化类时,注入结果到构造方法中
idArg - ID 参数;标记出作为 ID 的结果可以帮助提高整体性能
arg - 将被注入到构造方法的一个普通结果
id – 一个 ID 结果;标记出作为 ID 的结果可以帮助提高整体性能
result – 注入到字段或 JavaBean 属性的普通结果
association – 一个复杂类型的关联;许多结果将包装成这种类型
嵌套结果映射 – 关联可以是 resultMap 元素,或是对其它结果映射的引用
collection – 一个复杂类型的集合
嵌套结果映射 – 集合可以是 resultMap 元素,或是对其它结果映射的引用
discriminator – 使用结果值来决定使用哪个 resultMap
case – 基于某些值的结果映射,嵌套结果映射 – case 也是一个结果映射,因此具有相同的结构和元素;或者引用其它的结果映射
多对一:
一个老师多个学生,对于学生而言,就是多对一的关系
<mapper namespace="dao.StudentMapper">
<!-- 方式一: 按查询嵌套处理,select嵌套查询-->
<select id="getTeacher" resultType="pojo.teacher">
select * from teacher where id=#{tid}
</select>
<resultMap id="studentResult" type="pojo.student">
<!– 对象用association–>
<result property="id" column="id"></result>
<result property="name" column="name"></result>
<association property="teacher" column="tid" javaType="pojo.teacher" select="getTeacher">
</association>
</resultMap>
<select id="getStudent" resultMap="studentResult">
select * from student
</select>
<!-- 方式二:按照结果嵌套处理,联表查询-->
<resultMap id="studentResult2" type="pojo.student">
<result property="id" column="id"></result>
<result property="name" column="name"></result>
<association property="teacher" javaType="pojo.teacher">
<result property="name" column="tname"></result>
</association>
</resultMap>
<select id="getStudent2" resultMap="studentResult2">
select s.id,s.name,t.name tname from student s,teacher t
where s.tid=t.id
</select>
</mapper>
一对多:
一个老师多个学生;对于老师而言,就是一对多的关系
<mapper namespace="dao.TeacherMapper">
<!-- 按结果查询-->
<resultMap id="teacherResult" type="pojo.teacher" >
<result property="id" column="td"></result>
<result property="name" column="tname"></result>
<!-- 集合中的泛型oftype-->
<collection property="studentList" ofType="pojo.student">
<result property="id" column="sid"></result>
<result property="name" column="sname"></result>
</collection>
</resultMap>
<select id="getTeacher" resultMap="teacherResult" parameterType="int">
select t.name tname, s.id sid,s.name sname,t.id td
from student s , teacher t
where t.id=s.tid and t.id = #{tid}
</select>
<!-- 子查询-->
<select id="getStudentBytid" resultType="pojo.student">
select * from student where tid=#{td}
</select>
<resultMap id="teacherResult" type="pojo.teacher">
<collection property="studentList" javaType="ArrayList" select="getStudentBytid" ofType="pojo.student" column="id">
</collection>
</resultMap>
<select id="getTeacher" resultMap="teacherResult">
select * from teacher
where id=#{tid}
</select>
</mapper>
小结
- 关联 - association 【多对一】
- 集合 - collection 【一对多】
- javaType & ofType
- JavaType用来指定实体类中的类型
- ofType用来指定映射到List或者集合中的pojo类型,泛型中的约束类型
注意点:
- 保证SQL的可读性,尽量保证通俗易懂
- 注意一对多和多对一,属性名和字段的问题
- 如果问题不好排查错误,可以使用日志,建议使用Log4j