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属性赋值。