1:一对一的处理:作者表和博客表示一对一的关系
<select id="selectBlogWithAuthor" resultMap="blogResultWithAuthor">
SELECT
b.id as blog_id,
b.name 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>
<resultMap id="blogResultWithAuthor" type="blog">
<id property="id" column="blog_id"/>
<result property="name" 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>
1> 首先看到的是select标签,其中id表示对应的接口的方法名。
resultMap的值是一个resultMap节点的id,这个表示select查询结果的映射方式。
2> 然后就是resultMap最后所指向的节点blogResultWithAuthor。
- resultMap节点的id就是唯一标识这个节点的,type表示这个resultMap最终映射成的实体类Blog。
- id是主键映射,这个和mybatis缓存有关。
对于resultMap id=authorResult 也是一样的。
2: 对于一对多的处理: 生命博客表和博文表是一对多的关系
<select id="selectBlogWithPost" resultMap="blogResultWithPost">
SELECT
b.id AS blog_id,
b.name AS blog_name,
b.author_id AS blog_author_id,
p.id AS post_id,
p.subject AS post_subject,
p.body AS post_body
FROM blog b
LEFT OUTER JOIN post p ON b.id=p.blog_id
WHERE b.id=#{id}
</select>
<resultMap id="blogResultWithPost" type="Blog">
<id property="id" column="blog_id"/>
<result property="name" column="blog_name"/>
<collection property="posts" ofType="Post">
<id property="id" column="post_id"/>
<result property="subject" column="post_subject"/>
<result property="body" column="post_body"/>
</collection>
</resultMap>
集合和关联几乎完全一样,只不过一个是association一个是collection,一个是一对一,一个是一对多, 对于collection中的一些参数。
注意:
这个对你所映射的内容没有深度,广度或关联和集合相联合的限制。当映射它们 时你应该在大脑中保留它们的表现。 你的应用在找到最佳方法前要一直进行的单元测试和性 能测试。 只是一个简单的了解, 还需深入学习。
对于复用的部分可以参考:http://www.cnblogs.com/woshimrf/p/5697617.html#association