今天学习的是mybatis的映射,这里比较重要的是resultMap,其实resultType背后就是通过resultMap将取出的字段自动映射到java bean的对应属性上的。所以resultMap就是对数据映射到java对象上的描述。
下面是我学习的例子:一个Blog类,一个Author类,一个Blog对应一个Author。
Blog定义如下:
public class Blog {
private int id;
private String title;
private Author author;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Author getAuthor() {
return author;
}
public void setAuthor(Author author) {
this.author = author;
}
public String toString() {
StringBuffer buffer = new StringBuffer();
buffer.append("Id : ").append(id);
buffer.append("\tTitle : ").append(title);
buffer.append("\tAuthor :[").append(author).append("]");
return buffer.toString();
}
}
Author:
package com.leecode.mybatis.association.model;
public class Author {
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String toString() {
StringBuffer buffer = new StringBuffer();
buffer.append("Id : ").append(id);
buffer.append("\tName : ").append(name);
return buffer.toString();
}
}
mybatis可以通过两种方式来加载关联关系:1.嵌套查询(select),2.嵌套结果(result)。
嵌套查询是指通过执行另一个SQL映射来获得期望的结果类型,如下所示:
<resultMap id="blogResult" type="Blog">
<association property="author" column="author_id" javaType="Author" select="selectAuthor" />
</resultMap>
<select id="selectBlog" parameterType="int" resultMap="blogResult">
select * from T_BLOG
where id = #{id}
</select>
<select id="selectAuthor" parameterType="int" resultType="Author">
select * from t_author
where id = #{id}
</select>
在id为blogResult的resultMap中通过association中的select属性指定Blog的属性author需要通过id为“selectAuthor”的SQL映射来查询,column属性表明根据t_author中的author_id字段查询author。这种查询会有“N+1”查询问题。
嵌套结果可以通过多表连接查询来简化映射:
<select id="getBlog" parameterType="int" resultMap="blogInfo">
select
blog.id as blog_id,
blog.title as blog_title,
blog.author_id as blog_author_id,
author.id as author_id,
author.name as author_name
from T_BLOG blog left outer join T_AUTHOR author on blog.author_id = author.id
where blog.id = #{id}
</select>
<resultMap id="blogInfo" type="Blog">
<id property="id" column="blog_id" />
<result property="title" column="blog_title" />
<!-- 关联author属性 -->
<association property="author" column="blog_author_id" javaType="Author" resultMap="authorInfo" />
</resultMap>
<resultMap id="authorInfo" type="Author">
<id property="id" column="author_id" />
<result property="name" column="author_name" />
</resultMap>
因为T_BLOG和T_AUTHOR表中都有“id”这个字段,所以需要重命名以确保结果集中字段名称都唯一。