MyBatis多表映射demo
三个实体类,作者、文章和评论。 public class Author {
private int id;
private String username;
private String nickname;
private LocalDate birthday;
private LocalDateTime registerTime;
} public class Article {
private int id;
private String title;
private String content;
private Author author;
private List<Comment> comments;
private LocalDateTime createTime;
private LocalDateTime modifyTime;
} public class Comment {
private int id;
private String content;
private Author author;
private Article article;
private LocalDateTime createTime;
}
相应的数据表如下: CREATE TABLE author (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(255) NOT NULL UNIQUE,
nickname VARCHAR(255),
birthday DATE,
register_time DATETIME NOT NULL );
CREATE TABLE article (
id INT AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(255) NOT NULL,
content TEXT NOT NULL,
author INT NOT NULL,
create_time DATETIME NOT NULL,
modify_time DATETIME NOT NULL,
FOREIGN KEY (author) REFERENCES author (id) );
CREATE TABLE comment (
id INT AUTO_INCREMENT PRIMARY KEY,
author INT NOT NULL,
article INT NOT NULL,
content TINYTEXT NOT NULL,
create_time DATETIME NOT NULL,
FOREIGN KEY (author) REFERENCES author (id),
FOREIGN KEY (article) REFERENCES article (id)
);
映射结果
在前面的例子中,由于是简单的一对一单表映射,所以直接使用resultType属性指定需要映射的结果。
但是如果是复杂的例子,或者列名和属性名不对应,那么这种情况就不行了。这时候需要改为使用另一个属性resultMap来映射结果。
resultMap属性需要指定一个resultMap的ID。在resultMap中我们需要指定结果的映射,如果列名和属性名相同的话还可以省略映射。id用于映射主键,result用于映射其他属性。
<!--查询作者-->
<select id="selectAuthor" resultMap="authorResult">
SELECT
id,
username,
nickname,
birthday,
register_time
FROM author
WHERE id = #{id}
</select>
<!--作者结果映射-->
<resultMap id="authorResult" type="Author">
<id property="id" column="id"/>
<result property="registerTime" column="register_time"/>
</resultMap>
结果的关联
上面的例子演示了如何使用resultMap。下面我们来看看如何关联结果。假设我们现在要查询文章,由于文章表中有一个作者的外键,文章实体类也有作者的引用。因此简单的查询在这里并不适用。我们需要使用关联来将文章和作者关联起来,有两种方式:嵌套查询关联和嵌套结果关联。
嵌套查询关联
这是一种非常简单的方式,非常易于理解。嵌套查询关联需要使用association元素,并指定select属性。select属性指定另一个查询的ID,MyBatis会在每一条记录上使用该查询再执行一次嵌套查询以获取结果。
<!--查询文章-->
<select id="selectArticle" resultMap="articleMap">
SELECT
id,
title,
content,
author,
create_time,
modify_time
FROM article
WHERE id = #{id}
</select>
<!--嵌套查询关联文章表-->
<resultMap id="articleMap" type="Article">
<id property="id" column="id"/>
<result property="createTime" column="create_time"/>
<result property="modifyTime" column="modify_time"/>
<association property="author" column="author" select="selectAuthor"/>
</resultMap> 但是这种方式有一个问题,就是著名的N+1问题。我们要获得一些文章,需要执行一条SQL语句(这就是1),然后对于每条文章,我们还得执行一次查询来获得作者的信息(这就是N)。在查询数据量较大的时候会显著影响性能。为了避免这个问题,我们需要使用下面的方式:嵌套结果关联。 嵌套结果关联 嵌套结果关联其实就是我们在编写SQL语句的时候直接编写多表查询。如果有重名的列我们可以考虑添加前缀来解决名称冲突问题。需要注意这次我们在association元素添加的不是select属性了。而是resultMap属性。因为文章表和作者表存在重名属性,所以我们需要在SQL语句中使用as子句修改列名,同时使用columnPrefix="a_"来指定列前缀。这样MyBatis才能正确识别。 另外一个需要注意的地方是默认情况下MyBatis的autoMappingBehavior是PARTIAL,也就是说MyBatis会自动映射单表属性,但是遇到这种关联结果就不会自动映射。因此我们在确认没有重复名称之后就可以手动设置autoMapping="true",覆盖MyBatis的全局配置。一般情况下autoMappingBehavior的值不要指定为FULL,除非你确定所有表的所有字段不会出现重复。在我们这个例子中,如果去掉表前缀并让MyBatis自动映射所有字段,你会发现作者ID和文章ID会被错误的设置为同一个ID。 <select id="selectArticle" resultMap="articleMap">
SELECT
article.id,
title,
content,
author,
create_time,
modify_time,
author.id AS a_id,
username AS a_username,
nickname AS a_nickname,
birthday AS a_birthday,
register_time AS a_register_time
FROM article, author
WHERE article.id = #{id} AND author.id = article.author
</select>
<!--嵌套查询关联文章表-->
<resultMap id="articleMap" type="Article" autoMapping="true">
<id property="id" column="id"/>
<result property="createTime" column="create_time"/>
<result property="modifyTime" column="modify_time"/>
<association property="author" column="author"
resultMap="authorMap" columnPrefix="a_"/>
</resultMap> 我们可以看到嵌套结果比嵌套查询要复杂很多。这是为了性能而不得已的折中方案。另外在结果映射中最好显式指定主键,由于主键可以唯一标识行,能让MyBatis以更好的性能来映射结果。 结果的集合 有时候一个实体类会包含另一个实体类的集合。例如上面的文章类包含了一个评论集合。这时候就需要另外一种方式将集合映射到结果了。 嵌套查询集合 嵌套查询集合和嵌套查询关联非常类似,只不过把association元素改为collection元素即可。和嵌套查询关联一样,嵌套查询集合也有N+1性能问题。在数据量大的时候最好不要使用。 在嵌套查询集合中,需要额外添加一个属性ofType,指定结果中元素的类型。对于每一条记录,MyBatis会调用指定的查询,查询出一个集合,并传给要映射的类型。 <!--嵌套查询关联文章表-->
<resultMap id="articleMap" type="Article" autoMapping="true">
<result property="createTime" column="create_time"/>
<result property="modifyTime" column="modify_time"/>
<collection property="comments" column="id"
ofType="Comment" select="selectCommentsByArticle"/>
</resultMap>
<!--查找评论-->
<select id="selectCommentsByArticle"
resultMap="commentMap">
SELECT
id,
content,
create_time
FROM comment
WHERE article = #{id}
</select>
<resultMap id="commentMap" type="Comment" autoMapping="true">
<id property="id" column="id"/>
<result property="createTime" column="create_time"/>
</resultMap> 嵌套结果集合 嵌套结果集合和嵌套结果关联类似。但是由于这次不是一对一的关联映射,而是一对多的集合映射。所以我们只能使用外连接来编写SQL语句。同样的,为了区分重名的行,我们需要添加列前缀。另外评论类还有几个外键,这里为了简便就不进行查询和映射了。如果再添加外键的映射,SQL语句就会变得更长。 <select id="selectArticle" resultMap="articleMap">
SELECT
article.id,
title,
article.content,
article.author,
article.create_time,
modify_time,
comment.id AS c_id,
comment.content AS c_content,
comment.create_time AS c_create_time
FROM article
LEFT JOIN comment ON article.id = comment.article
WHERE article.id = #{id}
</select>
<!--嵌套查询关联文章表-->
<resultMap id="articleMap" type="Article" autoMapping="true">
<id property="id" column="id"/>
<result property="createTime" column="create_time"/>
<result property="modifyTime" column="modify_time"/>
<collection property="comments" column="id"
ofType="Comment" resultMap="commentMap"
columnPrefix="c_"/>
</resultMap> MyBatis中最麻烦的地方就是这些映射了。在编写映射的时候我们必须非常小心,最好使用单元测试来帮助我们一步一步核对映射的正确性。 测试一下 前面介绍了单表映射,关联映射,集合映射等几种映射方式。下面我们来看看MyBatis文档中的一个例子。这是一个很长的SQL语句和相应的结果映射。如果你完全看懂了,就说明你已经完全掌握了MyBatis最核心最重要的功能了。 <!-- Very Complex Statement -->
<select id="selectBlogDetails" resultMap="detailedBlogResultMap">
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_password,
A.email as author_email,
A.bio as author_bio,
A.favourite_section as author_favourite_section,
P.id as post_id,
P.blog_id as post_blog_id,
P.author_id as post_author_id,
P.created_on as post_created_on,
P.section as post_section,
P.subject as post_subject,
P.draft as draft,
P.body as post_body,
C.id as comment_id,
C.post_id as comment_post_id,
C.name as comment_name,
C.comment as comment_text,
T.id as tag_id,
T.name as tag_name
from Blog B
left outer join Author A on B.author_id = A.id
left outer join Post P on B.id = P.blog_id
left outer join Comment C on P.id = C.post_id
left outer join Post_Tag PT on PT.post_id = P.id
left outer join Tag T on PT.tag_id = T.id
where B.id = #{id}
</select> 对应的映射文件。 <!-- Very Complex Result Map -->
<resultMap id="detailedBlogResultMap" type="Blog">
<constructor>
<idArg column="blog_id" javaType="int"/>
</constructor>
<result property="title" column="blog_title"/>
<association property="author" 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"/>
<result property="favouriteSection" column="author_favourite_section"/>
</association>
<collection property="posts" ofType="Post">
<id property="id" column="post_id"/>
<result property="subject" column="post_subject"/>
<association property="author" javaType="Author"/>
<collection property="comments" ofType="Comment">
<id property="id" column="comment_id"/>
</collection>
<collection property="tags" ofType="Tag" >
<id property="id" column="tag_id"/>
</collection>
</collection>
</resultMap>
MyBatis多表映射demo的更多相关文章
- MyBatis快速入门(1):搭建环境和单表映射
一.MyBatis简介 一说起对象关系映射框架,大家第一时间想到的肯定是Hibernate.Hibernate作为一个著名的框架,功能十分强大.我们只需要配置好实体类和数据表之间的关系,Hibe ...
- 5.Mybatis的输出映射(就是对查询的结果集的映射)
Mybatis的输出映射,也就是对查询结果集的一个映射,主要有两种: 1.resultType(不需要配置,可以直接用) 一般是实体类 基本类型也可以 2.resultMap(需要配置resultMa ...
- MyBatis 多表联合查询及优化 以及自定义返回结果集
下面就来说一下 mybatis 是通过什么来实现多表联合查询的.首先看一下表关系,如图: 这 里,我已经搭好了开发的环境,用到的是 SpringMVC + Spring + MyBatis,当然,为了 ...
- 【Mybatis】MyBatis之表的关联查询(五)
本章介绍Mybatis之表的关联查询 一对一关联 查询员工信息以及员工的部门信息 1.准备表employee员工表,department部门表 CREATE TABLE `employee` ( `i ...
- MyBatis实战之映射器
映射器是MyBatis最强大的工具,也是我们使用MyBatis时用得最多的工具,因此熟练掌握它十分必要.MyBatis是针对映射器构造的SQL构建的轻量级框架,并且通过配置生成对应的JavaBean返 ...
- MyBatis从入门到精通(十一):MyBatis高级结果映射之一对多映射
最近在读刘增辉老师所著的<MyBatis从入门到精通>一书,很有收获,于是将自己学习的过程以博客形式输出,如有错误,欢迎指正,如帮助到你,不胜荣幸! 本篇博客主要讲解MyBatis中如何使 ...
- 04—mybatis的关联映射
mybatis的关联映射一对一一对多多对多 一.一对一(一个人只能有一个身份证号) 1.创建表创建表tb_card CREATE TABLE `tb_card` ( `id` int(11) NOT ...
- Mybatis高级结果映射
有时侯,我们用SQL取得的结果需要映射到类似Map<key, Bean>这样的数据结构中或是映射到多个实体类中时,我们就需要使用到resultMap.下面用3个例子说明Mybatis高级结 ...
- Mybatis(二) SQL映射文件
SQL映射文件 单条件查询 1. 在UserMapper接口添加抽象方法 //根据用户名模糊查询 List<User> getUserListByName(); 2. 在UserMappe ...
随机推荐
- 分享知识-快乐自己:FastDFS详解
在使用fdfs之前,需要对其有一定的了解,这篇文章作为准备篇,将针对fdfs的简介,功能性,使用场景等方面进行介绍 一):起源 淘宝网开放平台技术部资深架构师余庆先生首先回顾了自己在Yahoo工作时的 ...
- time模块详解
本文转自这里: 在Python中,与时间处理有关的模块就包括:time,datetime以及calendar.这篇文章,主要讲解time模块. 在开始之前,首先要说明这几点: 在Python中,通常有 ...
- bootstrap 操作提示placeholder
Javascript 部分 function checkForDefaultAlertPlaceholder() { if ($("#alertPlaceholder").leng ...
- Sturts2 三种开发模式 (转)
1.实现与 Servlet API的交互struts2中提供了Map类型的request.session与application,可以从ActionContext对象中获得.ActionContext ...
- 用工具快速建立hibernate框架
,一.建好项目后先导入两类jar包,一类是hibernate的jar包,一类是jdbc的jar包 二.点击“窗口”--“显示视图”--“其它”-“Hibernate configurations” 三 ...
- ElasticSearch安装及简单配置说明
目录 1. 准备安装包... 1 2. 安装jdk7. 1 3. 安装ElasticSearch. 2 4. 安装maven. 3 5. 集成IK ...
- 血的教训 password写成passward,教训应该从首页赋值 参数名
血的教训 password写成passward,教训应该从首页赋值 参数名
- 使用macbook破解WPA/WPA2 wifi密码
文本仅供学习交流. 我使用的系统是macbook pro 15: 安装aircrack-ng 使用homebrew安装,命令: brew install aircrack-ng 抓包-抓取带密码的握手 ...
- 记录最近工作使用javascript对select[option]的操作
1: 数据库取值赋予select选项 $(function(){ $("input[name='state'][value='{$store.state}']").attr(&qu ...
- vc++ windows 快速启动栏创建快捷方式
创建快速启动栏 在windows软件开发中,软件安装过程中总是需要在快速启动栏创建快捷方式,下面介绍一种快速启动栏创建快捷方式的方法,具体代码如下:(该方法不支持win10,目前还没有找到win10的 ...