Mybaties的關聯映射(嵌套結果映射,嵌套查詢映射)

1.嵌套查詢映射(不提倡,查詢兩次,會產生N+1問題@):

<resultMap id=”blogResult” type=”Blog”>       

  <association property="author" column="blog_author_id"    javaType="Author" select=”selectAuthor” />   

 </resultMap>                                                                                             

<select id=”selectBlog” parameterType=”int” resultMap=”blogResult”>      

  SELECT * FROM BLOG WHERE ID = #{id}

    </select>       

 <select id=”selectAuthor” parameterType=”int” resultType="Author">    

     SELECT * FROM AUTHOR WHERE ID = #{id}    

</select>

有兩個查詢語句:一個來加載博客,另外一個來加載作者,而且博客的結果映射描述了“selectAuthor”語句應該被用來加載它的 author 屬性。

其他所有的屬性將會被自動加載,假設它們的列和屬性名相匹配

2.嵌套結果映射(可以解決N+1問題):

<resultMap id="deptEmpsResult" type="Dept">

<id property="deptno" column="DEPTNO">

<result property="dname" column="DNAME"/>

<result property="loc" column="LOC"/>

<collection property="emps" ofType="Emp">

<id property="empno" column="EMPNO"/>

<result property="ename" column="ENAME"/>

<result property="job" column="JOB"/>

<result property="mgr" column="MGR"/>

<result property="hireDate" column="HIREDATE"/>

</collection>

</resultMap>

 

<select id="findById" parameterType="int" resultMap="deptEmpsResult">

select 

d.DEPTNO,d.DNAME,d.LOC,e.EMPNO,e.ENAME,e.SAL,e.MGR,e.COMM,e.HIREDATE,e.JOB

from

DEPT d join EMP e on (d.DEPTNO=e.DEPTNO)

where 

d.DEPTNO=#{deptno}

</select>

  

  上面映射信息,當利用findById查詢時,會執行關聯查詢SQL,然後MyBatis負責將結果數據提取, DEPT字段值封裝成Dept對象,EMP字段值封裝成Emp對象集合,然後Emp對象集合給Dept對象的emps屬性賦值。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章