Mybatis 高级结果映射 ResultMap Association Collection
Mybatis处理复杂Sql(association/collection)
- 多对一
- 多个学生,对应一个老师
- 学生:关联--多个学生关联一个老师(多对一)
- 老师:集合--一个老师有很多学生(一对多)
1.1、按照查询嵌套处理
<select id="getStudent" resultMap="StudentTeacher">
select * from student
</select>
<resultMap id="StudentTeacher" type="Student">
<result column="id" property="id"/>
<result column="name" property="name"/>
<!--复杂属性单独处理
对象:association
集合:collection
-->
<association property="teacher" column="tid" javaType="Teacher" select="getTeacher"/>
<collection property=""/>
</resultMap>
<select id="getTeacher" resultType="Teacher">
select * from teacher where id = #{tid};
</select>
1.2、按照结果嵌套处理
<select id="getStudent2" resultMap="StudentTeacher2">
select s.id sid,s.name sname,t.name tname
from student s,teacher t
where s.id = t.id
</select>
<resultMap id="StudentTeacher2" type="Student">
<result column="sid" property="id"/>
<result column="sname" property="name"/>
<!--复杂属性单独处理
对象:association
集合:collection
-->
<association property="teacher" javaType="Teacher">
<result column="tname" property="name"/>
</association>
<collection property=""/>
</resultMap>
-
一对多
<select id="getTeacher"resultMap="TeacherStudent">
select s.id sid,s.name sname,t.name tname,t.id tid
from student s,teacher t
where s.tid = t.id = #{tid}
</select>
<resultMap id="TeacherStudent" type="Teacher">
<result property="id" column="tid"/>
<result property="name" column="tname"/>
<collection property="students" ofType="Student">
<result column="sid" property="id"/>
<result column="sname" property="name"/>
<result column="tid" property="tid"/>
</collection>
</resultMap>
本文来自博客园,作者:六爻呈乾,转载请注明原文链接:https://www.cnblogs.com/ilycq/p/13851655.html