Mybatis联合查询
为什么80%的码农都做不了架构师?>>>
案例
一个博客系统中,用户可以任意发表博文(Post),用户还可以对博文进行评论(Comment)。于是在这个系统中,存在以下的关系:
在数据库中,Author,Post和Comment存在于不同的表中。但Comment会使用外键关联Post,而Post又会外键关联Author。
create table author (id int primary key,name varchar(20)
);create table post (id int primary key,authorId int,title varchar(100),created timestamp,content text,foreign key (authorId) REFERENCES author(id)
);create table comment (id int primary key,postId int,content text,created timestamp,foreign key (postId) REFERENCES post(id)
);
在java类中,Author, Post和Comment分别对应的java类型为:
public class Post {private int id;private Author author;private String title;private String content;private Timestamp created;private List<Comment> comments;// getters and setters
}public class Author {private int id;private String name;// getters and setters
}public class Comment {private int id;private int postId;private String content;private Timestamp created;// getters and setters
}
下面使用Mybatis的联合查询,创建一个Post实例,其中comments会自动填充到Post的comments表中。
联合查询
首先给出mybatis的配置:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration><typeAliases><typeAlias type="com.test.Post" alias="Post" /><typeAlias type="com.test.Author" alias="Author" /><typeAlias type="com.test.Comment" alias="Comment" /></typeAliases><environments default="development"><environment id="development"><transactionManager type="jdbc" /><dataSource type="POOLED"><property name="driver" value="com.mysql.jdbc.Driver" /><property name="url" value="jdbc:mysql://localhost:3306/joey" /><property name="username" value="mysql" /><property name="password" value="mysql" /></dataSource></environment></environments><mappers><mapper resource="com/test/my/BlogMapper.xml" /></mappers>
</configuration>
以及SessionManager工厂类:
public class SessionManager {private static SqlSessionFactory sessionFactory;public static synchronized SqlSessionFactory getSessionFactory() {if (sessionFactory != null) return sessionFactory;String resource = "com/lux/stat/dest/mybatis-conf.xml";try {sessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsReader(resource));} catch (IOException e) {e.printStackTrace();}return sessionFactory;}
}
还有BlogMapper接口:
public interface BlogMapper {public Post getPostById(int id);public List<Post> getPosts();
}
最后是测试用main函数:
public class Test {public static void main(String[] args) {// initData();SqlSession session = SessionManager.getSessionFactory().openSession();BlogMapper mapper = session.getMapper(BlogMapper.class);Post post = mapper.getPostById(1);System.out.println(post.getAuthor().getName());System.out.println(post.getComments().size());System.out.println(post.getComments().get(0).getContent());List<Post> posts = mapper.getPosts();post=posts.get(0);System.out.println(post.getAuthor().getName());System.out.println(post.getComments().size());System.out.println(post.getComments().get(0).getContent());session.close();}
}
Mybatis联合查询提供了两种方式
方式一,嵌套查询
BlogMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.test.my.BlogMapper"><resultMap id="postResult" type="Post"><association property="author" column="authorId" javaType="Author" select="getAuthorById"/><collection property="comments" javaType="ArrayList" column="id" ofType="Comment" select="getCommentsById"/></resultMap><select id="getPostById" resultMap="postResult">select id, authorId, title, content, created from post where id=#{param1}</select><select id="getPosts" resultMap="postResult">select id, authorId, title, content, created from post</select><select id="getAuthorById" resultType="Author">select id, name from author where id=#{param1}</select><select id="getCommentsById" resultType="Comment">select id, content, created, postId from comment where postId=#{param1}</select>
</mapper>
此类方式的缺点是效率低。组合最后的实例,必须要执行多条语句。像本例的getPosts()方法,如果posts数目为n,那么执行sql的条数应该为1+n+n。
方式二,JOIN语句
BlogMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.test.my.BlogMapper"><resultMap id="postResult" type="Post"><id property="id" column="id" /><result property="title" column="title" /><result property="content" column="content" /><result property="created" column="created" /><association property="author" javaType="Author"><id property="id" column="authorId" /><result property="name" column="name" /></association><collection property="comments" javaType="ArrayList" ofType="Comment"><id property="id" column="commentId" /><result property="content" column="comment" /><result property="created" column="commentCreated" /></collection></resultMap><select id="getPosts" resultMap="postResult">select A.id, A.title, A.content, A.created, B.id as authorId, B.name, C.id as commentId, C.content as comment, C.created as commentCreatedfrom post A join author B on A.authorid=B.idjoin comment C on A.id = C.postId</select><select id="getPostById" resultMap="postResult">select A.id, A.title, A.content, A.created, B.id as authorId, B.name, C.id as commentId, C.content as comment, C.created as commentCreatedfrom post A join author B on A.authorid=B.idjoin comment C on A.id = C.postIdwhere A.id=#{param1}</select>
</mapper>
使用此种方法,可以一条join语句便组装好post实例。
转载于:https://my.oschina.net/xpbug/blog/324710
Mybatis联合查询相关推荐
- MyBatis框架 多表联合查询实现
三种方式: ①业务装配 对两个表编写单表查询语句,在业务层(Serivce)把查询的两个结果进行关联 ②使用Auto Mapping特性 在实现两表联合查询时通过别名完成映射,使用Maybatis的& ...
- 一个mybatis动态 SQL查询的完整小案例。包含多表联合查询。
多表联合查询 一个根据机场查询航线的例子.有两张表,机场表包含机场信息:机场id.机场名字.机场城市. 航班包含航线信息:航班id.飞机编号.飞行时间.票价.起飞机场id.降落机场id. 需要查询的结 ...
- Mybatis实现联合查询(六)
1. 疑问 在之前的章节中我们阐述了如何用Mybatis实现检查的查询,而我们实际的需求中,绝大部分查询都不只是针对单张数据表的简单查询,所以我们接下来要看一下Mybatis如何实现联合查询. 2. ...
- springboot+mybatis+mysql 多表联合查询
###springboot+mybatis+mysql 多表查询 这里有两张表 用户表和用户信息表user.info 两个实体类展示他们一对一的关系 通过springboot注解的方式实现多表联合查询 ...
- SpringBoot+MyBatis多表联合查询
SpringBoot+MyBatis多表联合查询 写在前面 联合查询在实际工作中用的并不多,因为很多表的数据比较大,或者说未来比较大的表,都要谨慎使用联合查询 数据准备 建表语句 create tab ...
- mybatis plus 查询排序,Mybatis Plus带多条件的多表联合、分页、排序查询
背景 使用mybatis-plus单表操作十分方便,但是多表联合查询感觉又回归到xml时代了,我个人比较喜欢注解的方式,但是xml要更灵活 问题点:多表多条件联合查询 时间段查询 分页查询 sprin ...
- MyBatis 多表联合查询及优化
关于优化 对于优化嘛,我这里简单的提几点,大家可以考虑一下.首先,就是对表的设计,在设计表初期,不仅仅要考虑到数据库的规范性,还好考虑到所谓的业务,以及对性能的影响,比如,如果从规范性角度考虑的话,可 ...
- mybatis学习五-mybatis的多表联合查询
1. 一对一的关系 首先先看数据库 tb_user tb_orders 执行这条sql: 也就是查询所有的订单, 并每一个订单都联系上用户数据, 并再一次附上订单的id 也就是说, 从后面看, 就是每 ...
- MyBatis关联查询、多条件查询
MyBatis关联查询.多条件查询 1.一对一查询 任务需求; 根据班级的信息查询出教师的相关信息 1.数据库表的设计 班级表: 教师表: 2.实体类的设计 班级表: public class Cla ...
最新文章
- 高数第七版_习题解答_3-2 考研题提示及答案
- 讲给23岁以上男生的生活方式
- 简单易懂,ThreadPoolExecutor参数说明
- 【重磅】ArcGIS 10.8手把手经典图文安装教程(附安装包全套装下载,亲测可用)
- poj2624 4th Point
- 基于matlab的fisher线性判别及感知器判别_基于嵌入表示的网络实体对齐方法进展概述...
- LeetCode 题 - 9 回文数
- mysql 的client_mysql(一)-客户端Client相关
- 分库分表解决方案之ShardingSphere
- 01-HTML基础与进阶-day4-录像250
- python开发自动化创建一个任务下发到手机_django2 +requests+ddt+unittest+HTMLestRunner接口自动化测试平台...
- ws配置 zuul_spring cloud zuul 服务网关
- kali中安装使用msfconsole
- 三维激光扫描后处理软件_三维激光扫描——钢结构形变检测的利器
- UVALive - 3713 - Astronauts(图论——2-SAT)
- html 插件 firefox,firefox插件 怎么在firefox里添加插件
- 用什么擦地最干净脑筋急转弯_你没想过的“脑筋急转弯”,才是启发孩子智力的法宝(附资源下载)...
- [flink]各种大厂开源案例
- 全民战疫,我们在行动!
- 优购小程序项目效果预览