高级结果映射
MyBatis 创建时的一个思想是:数据库不可能永远是你所想或所需的那个样子。 我们希望每个数据库都具备良好的第三范式或 BCNF 范式,可惜它们并不都是那样。 如果能有一种数据库映射模式,完美适配所有的应用程序,那就太好了,但可惜也没有。 而 ResultMap 就是 MyBatis 对这个问题的答案。
比如,我们如何映射下面这个语句?
1. <!-- 非常复杂的语句 -->
2. <select id="selectBlogDetails" resultMap="detailedBlogResultMap">
3. select
4. B.id as blog_id,
5. B.title as blog_title,
6. B.author_id as blog_author_id,
7. A.id as author_id,
8. A.username as author_username,
9. A.password as author_password,
10. A.email as author_email,
11. A.bio as author_bio,
12. A.favourite_section as author_favourite_section,
13. P.id as post_id,
14. P.blog_id as post_blog_id,
15. P.author_id as post_author_id,
16. P.created_on as post_created_on,
17. P.section as post_section,
18. P.subject as post_subject,
19. P.draft as draft,
20. P.body as post_body,
21. C.id as comment_id,
22. C.post_id as comment_post_id,
23. C.name as comment_name,
24. C.comment as comment_text,
25. T.id as tag_id,
26. T.name as tag_name
27. from Blog B
28. left outer join Author A on B.author_id = A.id
29. left outer join Post P on B.id = P.blog_id
30. left outer join Comment C on P.id = C.post_id
31. left outer join Post_Tag PT on PT.post_id = P.id
32. left outer join Tag T on PT.tag_id = T.id
33. where B.id = #{id}
34. </select>
你可能想把它映射到一个智能的对象模型,这个对象表示了一篇博客,它由某位作者所写,有很多的博文,每篇博文有零或多条的评论和标签。 我们先来看看下面这个完整的例子,它是一个非常复杂的结果映射(假设作者,博客,博文,评论和标签都是类型别名)。 不用紧张,我们会一步一步地来说明。虽然它看起来令人望而生畏,但其实非常简单。
1. <!-- 非常复杂的结果映射 -->
2. <resultMap id="detailedBlogResultMap" type="Blog">
3. <constructor>
4. <idArg column="blog_id" javaType="int"/>
5. </constructor>
6. <result property="title" column="blog_title"/>
7. <association property="author" javaType="Author">
8. <id property="id" column="author_id"/>
9. <result property="username" column="author_username"/>
10. <result property="password" column="author_password"/>
11. <result property="email" column="author_email"/>
12. <result property="bio" column="author_bio"/>
13. <result property="favouriteSection" column="author_favourite_section"/>
14. </association>
15. <collection property="posts" ofType="Post">
16. <id property="id" column="post_id"/>
17. <result property="subject" column="post_subject"/>
18. <association property="author" javaType="Author"/>
19. <collection property="comments" ofType="Comment">
20. <id property="id" column="comment_id"/>
21. </collection>
22. <collection property="tags" ofType="Tag" >
23. <id property="id" column="tag_id"/>
24. </collection>
25. <discriminator javaType="int" column="draft">
26. <case value="1" resultType="DraftPost"/>
27. </discriminator>
28. </collection>
29. </resultMap>
resultMap 元素有很多子元素和一个值得深入探讨的结构。 下面是resultMap 元素的概念视图。
