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