MyBatis 是目前广泛使用的数据持久层框架,它的灵活性是它能让开发者青睐的重要原因之一,而它的自定义结果集 ResultMap 无疑是灵活性的重要体现。今天带大家探索一下 ResultMap 的映射规则。
假设我们要做一个博客网站,一共有三张表:作者,文章,类型
作者类
public class Author {
private Integer id;
private String username;
private String password;
private List<Article> articles;
}
文章类
public class Article {
private Integer id;
private String title;
private String content;
private Author author;
private Type type;
}
类型类
public class Type {
private Integer id;
private String name;
}
作者和文章是一对多的关系,文章和类型是一对一的关系,下面我们来看一下在 MyBatis 中如何进行结果映射。
普通结果映射
<resultMap id="typeResultMap" type="com.ml.blog.bean.Type">
<id property="id" column="id" />
<result property="name" column="name"/>
</resultMap>
id
– 一个 ID 结果,标记出作为 ID 的结果可以帮助提高整体性能
result
– 注入到字段或 JavaBean 属性的普通结果
简单地说,id 指定主键列的封装规则,result 指定普通列的封装规则
property:对应的 Javabean 属性名称
column:数据库列名
一对一结果映射
<resultMap id="articleResultMap" type="com.ml.blog.bean.Article">
<id property="id" column="id" />
<result property="title" column="title"/>
<result property="content" column="content"/>
<association property="type" javaType="com.ml.blog.bean.Type">
<id property="id" column="id"/>
<result property="name" column="name"/>
</association>
</resultMap>
association
– 一个复杂类型的关联,许多结果将包装成这种类型
- 嵌套结果映射 – 关联可以是
resultMap
元素,或是对其它结果映射的引用
association 表示关联一个对象
property:对应的 Javabean 属性名称
javaType:对应的 Javabean 属性类型
一对多结果映射
<resultMap id="authorResultMap" type="com.ml.blog.bean.Author">
<id property="id" column="id"/>
<result property="username" column="username"/>
<result property="password" column="password"/>
<collection property="articles" ofType="com.ml.blog.bean.Article">
<id property="id" column="id" />
<result property="title" column="title"/>
<result property="content" column="content"/>
<association property="type" javaType="com.ml.blog.bean.Type">
<id property="id" column="id"/>
<result property="name" column="name"/>
</association>
</collection>
</resultMap>
collection
– 一个复杂类型的集合
- 嵌套结果映射 – 集合可以是
resultMap
元素,或是对其它结果映射的引用
collection 表示引用一个 List 集合
property:对应的 Javabean 属性名称
ofType:对应的集合泛型的类型
参考:MyBatis 官方文档
https://mybatis.org/mybatis-3/zh/index.html