MyBatis框架——关系映射(一对多、多对多、多对一查询)
关系映射
一、映射(多)对一、(一)对一的关联关系
1).使用列的别名
①.若不关联数据表,则可以得到关联对象的id属性
②.若还希望得到关联对象的其它属性。则必须关联其它的数据表
1.创建表:
员工表:
DROP TABLE IF EXISTS `tbl_employee`; CREATE TABLE `tbl_employee` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_name` varchar(255) DEFAULT NULL,
`gender` char(1) DEFAULT NULL,
`email` varchar(255) DEFAULT NULL,
`d_id` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `fk_emp_dept` (`d_id`),
CONSTRAINT `fk_emp_dept` FOREIGN KEY (`d_id`) REFERENCES `tbl_dept` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
部门表:
CREATE TABLE tbl_dept(
id INT(11) PRIMARY KEY AUTO_INCREMENT,
dept_name VARCHAR(255)
)
2.创建相应的实体类和Mapper接口!
3.写关联的SQL语句
SELECT e.`id` id , e.`user_name` user_name, e.`gender` gender,e.`d_id` d_id,d.`id` did,d.`dept_name` dept_name
FROM `tbl_employee` e, tbl_dept d
WHERE e.`d_id` = d.`id` AND e.id = 1
4.在sql映射文件中写映射sql语句
方法一:【联合查询:级联属性封装结果集】
<!-- 联合查询:级联属性封装结果集 -->
<resultMap type="com.neuedu.entity.Employee" id="getEmployeeAndDeptMap">
<id column="id" property="id"/>
<result column="user_name" property="userName"/>
<result column="gender" property="gender"/>
<result column="email" property="email"/>
<result column="did" property="depart.id"/>
<result column="dept_name" property="depart.deptName"/>
</resultMap> <!-- public Employee getEmployeeAndDept(Integer id); -->
<select id="getEmployeeAndDept" resultMap="getEmployeeAndDeptMap">
SELECT e.`id` id , e.`user_name` user_name, e.`gender` gender,e.`email` email,e.`d_id` d_id,d.`id` did,d.`dept_name` dept_name
FROM `tbl_employee` e, tbl_dept d
WHERE e.`d_id` = d.`id` AND e.id = #{id}
</select>
注意:即使使用resultMap来映射,对于“对一”关联关系可以不使用association
方法二:【使用association来定义关联对象的规则,[比较正规的,推荐的方式]】
<!-- 联合查询:使用association封装结果集 -->
<resultMap type="com.neuedu.entity.Employee" id="getEmployeeAndDeptMap">
<id column="id" property="id"/>
<result column="user_name" property="userName"/>
<result column="gender" property="gender"/>
<result column="email" property="email"/>
<!--
association可以指定联合的javaBean对象
property="depart":指定哪个属性是联合的对象
javaType:指定这个属性对象的类型【不能省略】
-->
<association property="depart" javaType="com.neuedu.entity.Department">
<id column="did" property="id"/>
<result column="dept_name" property="deptName"/>
</association>
</resultMap> <!-- public Employee getEmployeeAndDept(Integer id); -->
<select id="getEmployeeAndDept" resultMap="getEmployeeAndDeptMap">
SELECT e.`id` id , e.`user_name` user_name, e.`gender` gender,e.`email` email,e.`d_id` d_id,d.`id` did,d.`dept_name` dept_name
FROM `tbl_employee` e, tbl_dept d
WHERE e.`d_id` = d.`id` AND e.id = #{id}
</select>
方法三:[上述结果相当于使用嵌套结果集的形式]【我们这里还可以使用Association进行分步查询】:
<!--
使用association进行分步查询
1.先按照员工id查询员工信息
2.根据查询员工信息中d_id值取部门表查出部门信息
3.部门设置到员工中:
-->
<select id="getDepartById" resultType="com.neuedu.entity.Department">
SELECT id ,dept_name deptName FROM tbl_dept WHERE id = #{id}
</select>
<resultMap type="com.neuedu.entity.Employee" id="myEmpByStep">
<id column="id" property="id"/>
<result column="user_name" property="userName"/>
<result column="gender" property="gender"/>
<result column="email" property="email"/>
<!--
association定义关联对象的封装规则
select:表明当前属性是调用指定的方法查出的结果
column:指定将哪一列的值传给这个方法 流程:使用select指定的方法(传入column指定的这列参数的值)查出对象,并封装给property指定的属性。
-->
<association property="depart" select="getDepartById" column="d_id"></association>
</resultMap>
<!-- public Employee getEmpAndDept(Integer id); -->
<select id="getEmpAndDept" resultMap="myEmpByStep">
select * from tbl_employee where id =#{id}
</select>
5.编写测试用例
public class TestMyBatis {
private SqlSession openSession = null; @Test
public void testGetEmployee(){
EmployeeMapperPlus mapper = openSession.getMapper(EmployeeMapperPlus.class);
Employee employee = mapper.getEmployeeAndDept(1);
System.out.println(employee);
} @Before
public void testBefore() throws IOException{
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
openSession= sqlSessionFactory.openSession();
} @After
public void testAfter(){
openSession.commit();
openSession.close();
} }
补充:懒加载机制【按需加载,也叫懒加载】:
<!--
在分步查询这里,我们还要讲到延迟加载:
Employee === > Dept:
我们每次查询Employee对象的时候,都将关联的对象查询出来了。
而我们想能不能我在需要部门信息的时候,再去查询,不需要的时候就不用查询了。
答案:可以的
我们只需要在分步查询的基础之上加上两个配置:
1.在mybatis的全局配置文件中加入两个属性:
<settings>
<setting name="mapUnderscoreToCamelCase" value="true"/>
<!-- 开启懒加载机制 ,默认值为true-->
<setting name="lazyLoadingEnabled" value="true"/>
<!-- 开启的话,每个属性都会直接全部加载出来;禁用的话,只会按需加载出来 -->
<setting name="aggressiveLazyLoading" value="false"/>
</settings> -->
测试:
@Test
public void testGetEmployee(){
EmployeeMapperPlus mapper = openSession.getMapper(EmployeeMapperPlus.class);
Employee employee = mapper.getEmpAndDept(1);
System.out.println(employee.getUserName());
}
此时:可以看到这里只发送了一条SQL语句。
注意:上面我们上面如果关联的是一个对象,我们还可以使用association标签,如果我们关联的是一个集合,
那么该使用谁呢?
二、映射对多的关联关系
场景二:查询部门的时候,将部门对应的所有员工信息也查询出来,注释在DepartmentMapper.xml中
第一种:使用collection嵌套结果集的方式:
1.修改Department实体类【添加Employee集合,并为该集合提供getter/setter方法】
public class Department {
private Integer id;
private String deptName; private List<Employee> list; public List<Employee> getList() {
return list;
}
public void setList(List<Employee> list) {
this.list = list;
}
......
}
建立DepartmentMapper接口文件,并添加如下方法:
public Department getDeptByIdPlus(Integer id);
2.sql映射文件中的内容为:【collection:嵌套结果集的方式:使用collection标签定义关联的集合类型元素的封装规则】
<!-- public Department getDeptByIdPlus(Integer id); -->
<resultMap type="com.neuedu.entity.Department" id="getDeptByIdPlusMap">
<id column="did" property="id"/>
<result column="dept_name" property="deptName"/>
<!--
collection:定义关联集合类型的属性的封装规则
ofType:指定集合里面元素的类型
-->
<collection property="list" ofType="com.neuedu.entity.Employee">
<!-- 定义这个集合中元素的封装规则 -->
<id column="eid" property="id"/>
<result column="user_name" property="userName"/>
<result column="email" property="email"/>
<result column="gender" property="gender"/>
</collection>
</resultMap> <select id="getDeptByIdPlus" resultMap="getDeptByIdPlusMap">
SELECT d.`id` did, d.`dept_name` dept_name,e.`id` eid,e.`user_name` user_name,e.`email` email,e.`gender` gender
FROM `tbl_dept` d
LEFT JOIN tbl_employee e
ON e.`d_id` = d.`id`
WHERE d.`id` = #{id}
</select>
3.测试方法为:
@Test
public void testGetEmployee(){
DepartmentMapper mapper = openSession.getMapper(DepartmentMapper.class);
Department department = mapper.getDeptByIdPlus(2);
System.out.println(department);
}
第二种:使用分步查询结果集的方式:
1.如果使用分步查询的话,我们的sql语句就应该为:
SELECT * FROM `tbl_dept` WHERE id = 2;
SELECT * FROM `tbl_employee` WHERE d_id = 2;
2.在DepartmentMapper接口文件中添加方法,如下所示:
public Department getDeptWithStep(Integer id);
3.再从EmployeeMapper接口中添加一个方法,如下所示:
public List<Employee> getEmployeeByDeptId(Integer deptId);
并在响应的sql映射文件中添加相应的sql语句
<select id="getEmployeeByDeptId" resultType="com.neuedu.entity.Employee">
select * from tbl_employee where d_id = #{departId}
</select>
4.在DepartmentMapper映射文件中:
<resultMap type="com.neuedu.entity.Department" id="getDeptWithStepMap">
<id column="id" property="id"/>
<result column="dept_name" property="deptName"/>
<collection property="list" select="com.neuedu.mapper.EmployeeMapper.getEmployeeByDeptId" column="id"></collection>
</resultMap>
<select id="getDeptWithStep" resultMap="getDeptWithStepMap">
SELECT id ,dept_name FROM tbl_dept WHERE id = #{id}
</select>
5.测试类:
@Test
public void testGetEmployee(){
DepartmentMapper mapper = openSession.getMapper(DepartmentMapper.class);
Department department = mapper.getDeptWithStep(2);
System.out.println(department);
}
6.总结:
映射(一)对多、(多)对多的关联关系=======》【映射"对多"的关联关系】
1.必须使用collection节点进行映射
2.基本示例:
注意:1). ofType指定集合中的元素类型
2).collection标签
映射多的一端的关联关系,使用ofType指定集合中的元素类型
columnprefix:指定列的前缀
使用情境:若关联的数据表和之前的数据表有相同的列名,此时就需要给关联的列其"别名".
若有多个列需要起别名,可以为所有关联的数据表的列都加上相同的前缀,然后再映射时指定前缀。
MyBatis框架——关系映射(一对多、多对多、多对一查询)的更多相关文章
- Hibernate框架关系映射一对多双向关联
直入主题,首先大配置常规配置, 这里住要说关联关系,大配置不多少,而且jar包默认添加好,笔者用的是idea2016. 然后我们知道关联关系主要是在小配置添加节点来配置属性.个人认为关联映射,就是对应 ...
- MyBatis加强(1)~myBatis对象关系映射(多对一关系、一对多关系)、延迟/懒加载
一.myBatis对象关系映射(多对一关系.一对多关系) 1.多对一关系: ---例子:多个员工同属于一个部门. (1)myBatis发送 额外SQL: ■ 案例:员工表通过 dept_id 关联 部 ...
- 第9章 MyBatis的关系映射
在实际开发中,对数据库的操作通常涉及多张表,涉及了对象和对象之间的关联关系.针对多表之间的操作,MyBatis提供了关联映射,通过关联映射就可以很好的处理对象与对象之间的关联关系 9.1 关联关系概述 ...
- 详谈Hibernate框架关系映射!
接触Hibernate也有一小段的时间了,愈发的觉得Hibernate是个神奇的东西,为什么这么说呢?因为你可以不懂一行sql,直接面向对象,就可以将数据直接保存到数据库去!! 你还可以保存一个对象, ...
- HIbernate学习笔记(五) 关系映射之一对多与多对一
三. 多对一 –单向 场景:用户和组:从用户角度来,多个用户属于一个组(多对一 关联) 使用hibernate开发的思路:先建立对象模型(领域模型),把实体抽取出来. 目前两个实体:用户和 ...
- Mybatis对象关系映射 one2one,one2many,many2many
MyBatis中的高级映射一般要借助select元素中的resultMap属性进行实现,通过此属性配置实现一对一,一对多等关系映射的实现 一对一映射:association 一对多映射:collect ...
- Mybatis框架基于映射文件和配置文件的方式,实现增删改查,可以打印日志信息
首先在lib下导入: 与打印日志信息有关的架包 log4j-1.2.16.jar mybatis架包:mybatis-3.1.1.jar 连接数据库的架包:mysql-connector-java-5 ...
- 框架应用:Mybatis (三) - 关系映射
你有一张你自己的学生证?(一对一) 你这一年级有多少个学生?(一对多) 班上学生各选了什么课?(多对多) 两张表以上的操作都需要联立多张表,而用SQL语句可以直接联立两张表,用工程语言则需要手动完成这 ...
- mybatis关系映射之一对多和多对一
本实例使用用户(User)和博客(Post)的例子做说明: 一个用户可以有多个博客, 一个博客只对应一个用户 一. 例子(本实体采用maven构建): 1. 代码结构图: 2. 数据库: t_user ...
随机推荐
- Chrome调试工具developer tool技巧
Chrome这个浏览器赞的不能再赞了,给前端的开发调试工作带来了极大的效率提升. Chrome的简洁.快速吸引了无数人,它的启动速度.页面解析速度都很快,同时得益于Google V8的快速,Javas ...
- 开启属于你的GNOME桌面
图片剪辑源自美剧<黑客军团>(英语:Mr. Robot) GNOME(GNU Network ObjectEnvironment)是一种GNU网络对象模型环境 ,GNU计划的一部分,目的为 ...
- 初学 Python(十二)——高阶函数
初学 Python(十二)--高阶函数 初学 Python,主要整理一些学习到的知识点,这次是高阶函数. #-*- coding:utf-8 -*- ''''' 话说高阶函数: 能用函数作为参数的函数 ...
- android调用系统相机进行视频录制并保存到指定目录
最近在做视频录制上传,调用的是系统的相机. 在做之前查了一些资料,发现好多人遇到保存到指定目录不成功的现象.自己写的时候就注意这些,最后发现他们遇到的问题我这边根本没有.可能是他们写法有问题吧. 下边 ...
- spring项目中service方法开启线程处理业务的事务问题
1.前段时间在维护项目的时候碰到一个问题,具体业务就是更新已有角色的资源,数据库已更新,但是权限控制不起效果,还是保留原来的权限. 2.排查发现原有的代码在一个service方法里有进行资源权限表的更 ...
- 教你上传本地代码到github
最近想起学Git,并且注册了Github. 将新创建的本地代码上传到github上,这里简单的记录一下,我喜欢使用命令行,这里全用命令行来实现,不了解Git命令的可以去了解下. 第一步:建立git仓库 ...
- [补档]Cube
Cube 题目 给你一个n×m的棋盘,有一个1×1×2的长方体竖直放在(1,1)上,你可以将其在棋盘上滚动,你的目标是让其竖直放在(n,m)上,问至少需要多少次操作.(放倒.竖直.翻滚) INPUT ...
- 表达式求值(二叉树方法/C++语言描述)(四)
代码清单 // binarytree.h #ifndef BINARYTREE_H #define BINARYTREE_H template <typename T> class Bin ...
- CocoaPods的一些略为高级一丁点的使用【转】
记得我刚开始做iOS开发的时候,是没有项目依赖管理工具.当需要引入第三方库的时候是相当麻烦的,不是直接拷贝库近来,就是添加依赖工程,直到CocoaPods出来才改变这个状况.项目依赖管理不是Cocoa ...
- C# 获取并判断操作系统版本,解决Win10、 Windows Server 2012 R2 读取失败的方案
Windows 8.1, Win10之后,通过GetVersion and GetVersionEx 方法获取WIndows操作系统版本号的功能需要添加manifest文件后才能查找到,不然的话会查找 ...