ibatis有两种加载关联关系的方法:
1. Nested Select:select另一个加载数据的sql语句id
<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>
在这里我们有两个select语句,一个去加载blog数据,另一个去加载author数据,在blog定义的resultMap中使用了加载
author的select语句,对blog中的author属性进行赋值。也就是说,这种简单的一对一关系,执行了两条select语句。
使用nested select会产生“N+1”问题,非常常见,性能消耗相当大,可以使用懒加载来解决,或者使用下面一种方法。
2.Nested Result:映射关联属性字段的resultMap id值,采用join的方式一次查询得出结果
<resultMap id="blogResult" type="Blog">
<id property="blog_id" column="id" />
<result property="title" column="blog_title" />
<association property="author" column="blog_author_id"
javaType="Author" resultMap="authorResult" />
</resultMap>
<resultMap id="authorResult" type="Author">
<id property="id" column="author_id" />
<result property="username" column="author_username" />
<result property="password" column="author_password" />
<result property="email" column="author_email" />
<result property="bio" column="author_bio" />
</resultMap>
或者:
<resultMap id="blogResult" type="Blog">
<id property="blog_id" column="id" />
<result property="title" column="blog_title" />
<association property="author" column="blog_author_id"
javaType="Author">
<id property="id" column="author_id" />
<result property="username" column="author_username" />
<result property="password" column="author_password" />
<result property="email" column="author_email" />
<result property="bio" column="author_bio" />
</association>
</resultMap>
在select语句中使用:
<select id="selectBlog" parameterType="int" resultMap="blogResult"> select
B.id as blog_id, B.title as blog_title, B.author_id as blog_author_id,
A.id as author_id, A.username as author_username, A.password as
author_password, A.email as author_email, A.bio as author_bio from
Blog B left outer join Author A on B.author_id = A.id where B.id =
#{id}
</select>