关联有嵌套查询和嵌套结果两种方式,本文是按照嵌套结果这种方式来说明的
上一章介绍了多对一的关系,用到了<association></association>,这是一个复杂类型的关联。我们选择一个示例来回顾下,比如:一个博客有一个用户,关联映射就工作于这种结果之上。首先看下,我们在本文中要用到的表结构字段:
- 博客
- blog : id title author_id
-
- 作者
- author: id username password email bio favourite_section
-
- 文章
- post :id blog_id author_id created_on section subject draft body
-
- 评论
- comment : id post_id name comment
-
- 标签
- T : id name
我们把一个博客和一个用户关联在一起,就像:
- <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_passowrd,
- a.email as auhtor_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>
注意这个联合查询,以及所有结果被唯一而清晰的名字而重命名。这使得映射非常简单。现在我们可以映射这个结果:
- <resultMap id="blogResult" type="Blog">
- <id property="id" column="blog_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>
在上面的例子中,你可以看到博客的作者关联authorResult 结果映射来加载作者实例。 上面的实例中,用了外部的结果映射元素来映射关联。这使得Author结果映射可以重用。然而,你不需要重用它的话,或者你仅仅引用你所有的结果映射到一个单独描述的结果映射中。你可以嵌套结果映射。这里给出使用这种方式的相同示例:
- <resultMap id="blogResult" type="Blog">
- <id property="id" column="blog_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>
上面你已经看到了如何处理有一个类型的关联.但是“有很多个”是怎样的呢?,也就是集合类型,本文的主要工作是来说这个的。
集合
相对于关联来说,集合映射多了一个属性”ofType“.这个属性用来区分
JavaBean(或字段)属性类型和
集合包含的类型来说是很重要的. ,ofType用来表示集合包含类型。
- <collection property="posts" ofType="Post">
- <id property="id" column="post_id"/>
- <result property="subject" column="post_subject"/>
- <result property="body" column="post_body"/>
- </collection>
集合元素的作用和关联几乎是相同的。我们来继续上面的示例,一个博客只有一个作者。但是博客有很多文章,在博客类中,这可以由下面的写法来表示:
- private List<Post> posts;
这一次联合博客表和文章表(一个blog_id可以对应很多的文章)SQL如下:
- <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,
- 再分享一下我老师大神的人工智能教程吧。零基础!通俗易懂!风趣幽默!还带黄段子!希望你也加入到我们人工智能的队伍中来!https://blog.csdn.net/jiangjunshow