集合的嵌套结果映射

现在你可能已经猜到了集合的嵌套结果映射是怎样工作的——除了新增的 “ofType” 属性,它和关联的完全相同。

首先, 让我们看看对应的 SQL 语句:

1. <select id="selectBlog" resultMap="blogResult">
2. select
3. B.id as blog_id,
4. B.title as blog_title,
5. B.author_id as blog_author_id,
6. P.id as post_id,
7. P.subject as post_subject,
8. P.body as post_body,
9. from Blog B
10. left outer join Post P on B.id = P.blog_id
11. where B.id = #{id}
12. </select>

我们再次连接了博客表和文章表,并且为每一列都赋予了一个有意义的别名,以便映射保持简单。 要映射博客里面的文章集合,就这么简单:

1. <resultMap id="blogResult" type="Blog">
2. <id property="id" column="blog_id" />
3. <result property="title" column="blog_title"/>
4. <collection property="posts" ofType="Post">
5. <id property="id" column="post_id"/>
6. <result property="subject" column="post_subject"/>
7. <result property="body" column="post_body"/>
8. </collection>
9. </resultMap>

再提醒一次,要记得上面 id 元素的重要性,如果你不记得了,请阅读关联部分的相关部分。

如果你喜欢更详略的、可重用的结果映射,你可以使用下面的等价形式:

1. <resultMap id="blogResult" type="Blog">
2. <id property="id" column="blog_id" />
3. <result property="title" column="blog_title"/>
4. <collection property="posts" ofType="Post" resultMap="blogPostResult" columnPrefix="post_"/>
5. </resultMap>

7. <resultMap id="blogPostResult" type="Post">
8. <id property="id" column="id"/>
9. <result property="subject" column="subject"/>
10. <result property="body" column="body"/>
11. </resultMap>