本章节主要介绍mybatis的resultMap的用法,包含了级联查询、关联查询、懒加载、鉴别器的相关讲解和代码用例
首先这是测试代码用到的实体类POJO
Employee.java:
package com.wcg.mybatis.entity;
import java.io.Serializable;
/**
* @author wcg
* @create 2019-05-06 10:04
*/
public class Employee implements Serializable {
private static final long serialVersionUID = -6248806586248836314L;
private Integer id;
private String lastName;
private String gender;
private String email;
private Department department;
public Employee() {
}
// setting getting 省略
@Override
public String toString() {
return "Employee{" +
"id=" + id +
", lastName='" + lastName + '\'' +
", gender='" + gender + '\'' +
", email='" + email + '\'' +
", department=" + department +
'}';
}
}
Department.java
package com.wcg.mybatis.entity;
import java.io.Serializable;
import java.util.List;
/**
* @author wcg
* @create 2019-05-07 23:59
*/
public class Department implements Serializable {
private static final long serialVersionUID = -6380361622841645277L;
private Integer id;
private String deptName;
private List<Employee> employeeList;
public Department() {
}
// setting getting 省略
@Override
public String toString() {
return "Department{" +
"id=" + id +
", deptName='" + deptName + '\'' +
", employeeList=" + employeeList +
'}';
}
}
数据库的建表语句DDL:
CREATE TABLE `tbl_employee` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`last_name` varchar(255) DEFAULT NULL,
`gender` char(1) DEFAULT NULL,
`email` varchar(255) DEFAULT NULL,
`dept_id` int(10) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8;
CREATE TABLE `tbl_department` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`dept_name` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
一、自定义结果集映射resultMap
EmployeeMapper.java 接口:
package com.wcg.mybatis.dao;
import com.wcg.mybatis.entity.Employee;
import org.apache.ibatis.annotations.MapKey;
import org.apache.ibatis.annotations.Param;
import java.util.List;
import java.util.Map;
/**
* @author wcg
* @create 2019-05-06 17:48
*/
public interface EmployeeMapperPlus {
Employee getEmpById(Integer id);
}
EmployeeMapper.xml sql映射文件:
<?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.wcg.mybatis.dao.EmployeeMapperPlus">
<!--
自定义某个javaBean的封装规则
type:自定义规则的Java类型
id:唯一id方便引用
-->
<resultMap id="employee" type="com.wcg.mybatis.entity.Employee">
<!--
指定主键列:
id定义主键会底层有优化;
column:字段
property:JavaBean属性
-->
<id column="id" property="id"></id>
<!-- 定义普通列封装规则 -->
<result column="last_name" property="lastName"></result>
<!-- 其他不指定的列会自动封装:我们只要写resultMap就把全部的映射规则都写上。 -->
<result column="gender" property="gender"></result>
<result column="email" property="email"></result>
</resultMap>
<!-- resultMap:自定义结果集映射规则; -->
<!-- Employee getEmpById(Integer id); -->
<select id="getEmpById" resultMap="employee">
select id,last_name,email,gender from tbl_employee where id = #{id}
</select>
</mapper>
测试代码:
package com.wcg.mybatis.test;
import com.wcg.mybatis.dao.EmployeeMapperPlus;
import com.wcg.mybatis.entity.Employee;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.io.InputStream;
/**
* @author wcg
* @create 2019-05-08 21:55
*/
public class ResultMapTest {
public SqlSessionFactory sessionFactory = null;
@BeforeEach
public void test()throws Exception{
// 根据全局配置文件(xml)创建一个SqlSessionFactory对象
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
}
@Test
public void resultMapTest(){
// 获取 SqlSession 的实例 。SqlSession 完全包含了面向数据库执行 SQL 命令所需的所有方法。通过 SqlSession 实例来直接执行已映射的 SQL 语句
SqlSession sqlSession = null;
try {
sqlSession = sessionFactory.openSession();
// 通过获取接口代理对象来执行sql语句
EmployeeMapperPlus mapper = sqlSession.getMapper(EmployeeMapperPlus.class);
Employee employee = mapper.getEmpById(2);
System.out.println(employee);
} finally {
// 资源关闭,放在finally中确保一定会执行
sqlSession.close();
}
}
}
测试结果:
DEBUG 05-08 22:43:39,908 ==> Preparing: select id,last_name,email,gender from tbl_employee where id = ? (BaseJdbcLogger.java:145)
DEBUG 05-08 22:43:39,989 ==> Parameters: 2(Integer) (BaseJdbcLogger.java:145)
DEBUG 05-08 22:43:40,022 <== Total: 1 (BaseJdbcLogger.java:145)
Employee{id=2, lastName='BB', gender='0', email='bb@qq.com', department=null}
二、级联属性封装结果集
EmployeeMapper.java 接口方法:
Employee getEmpByIdWithDeptName(Integer id);
EmployeeMapper.xml sql映射文件:
<?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.wcg.mybatis.dao.EmployeeMapperPlus">
<!--
联合查询:级联属性封装结果集
-->
<resultMap id="employeeWithDeptName" type="com.wcg.mybatis.entity.Employee">
<id column="eid" property="id"></id>
<result column="last_name" property="lastName"></result>
<result column="gender" property="gender"></result>
<result column="email" property="email"></result>
<result column="did" property="department.id"></result>
<result column="dept_name" property="department.deptName"></result>
</resultMap>
<select id="getEmpByIdWithDeptName" resultMap="employeeWithDeptName">
select
e.id as eid, e.last_name, e.email, e.gender,
d.id as did, d.dept_name
from
tbl_employee e
LEFT JOIN
tbl_department d on e.dept_id = d.id
where e.id = #{id}
</select>
</mapper>
测试代码:
@Test
public void resultMapTest(){
// 获取 SqlSession 的实例 。SqlSession 完全包含了面向数据库执行 SQL 命令所需的所有方法。通过 SqlSession 实例来直接执行已映射的 SQL 语句
SqlSession sqlSession = null;
try {
sqlSession = sessionFactory.openSession();
// 通过获取接口代理对象来执行sql语句
EmployeeMapperPlus mapper = sqlSession.getMapper(EmployeeMapperPlus.class);
Employee employee = mapper.getEmpById(2);
System.out.println(employee);
} finally {
// 资源关闭,放在finally中确保一定会执行
sqlSession.close();
}
}
测试结果:
DEBUG 05-08 22:51:26,592 ==> Preparing: select e.id as eid, e.last_name, e.email, e.gender, d.id as did, d.dept_name from tbl_employee e LEFT JOIN tbl_department d on e.dept_id = d.id where e.id = ? (BaseJdbcLogger.java:145)
DEBUG 05-08 22:51:26,676 ==> Parameters: 2(Integer) (BaseJdbcLogger.java:145)
DEBUG 05-08 22:51:26,700 <== Total: 1 (BaseJdbcLogger.java:145)
Employee{id=2, lastName='BB', gender='0', email='bb@qq.com', department=Department{id=1, deptName='开发部', employeeList=null}}
三、association定义关联对象封装结果集
(一)、普通查询
EmployeeMapper.java 接口方法:
Employee getByIdWithDept(Integer id);
EmployeeMapper.xml sql映射文件:
<?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.wcg.mybatis.dao.EmployeeMapperPlus">
<!--
使用association定义关联的单个对象的封装规则;
-->
<resultMap id="employeeWithDept" type="com.wcg.mybatis.entity.Employee">
<id column="eid" property="id"></id>
<result column="last_name" property="lastName"></result>
<result column="gender" property="gender"></result>
<result column="email" property="email"></result>
<!--
association可以指定联合的javaBean对象
property="dept":指定哪个属性是联合的对象
javaType:指定这个属性对象的类型[不能省略]
-->
<association property="department" javaType="com.wcg.mybatis.entity.Department">
<id column="did" property="id"></id>
<result column="dept_name" property="deptName"></result>
</association>
</resultMap>
<select id="getByIdWithDept" resultMap="employeeWithDept">
select
e.id as eid, e.last_name, e.email, e.gender,
d.id as did, d.dept_name
from
tbl_employee e
LEFT JOIN
tbl_department d on e.dept_id = d.id
where e.id = #{id}
</select>
</mapper>
测试代码:
@Test
public void associationTest(){
// 获取 SqlSession 的实例 。SqlSession 完全包含了面向数据库执行 SQL 命令所需的所有方法。通过 SqlSession 实例来直接执行已映射的 SQL 语句
SqlSession sqlSession = null;
try {
sqlSession = sessionFactory.openSession();
// 通过获取接口代理对象来执行sql语句
EmployeeMapperPlus mapper = sqlSession.getMapper(EmployeeMapperPlus.class);
Employee employee = mapper.getByIdWithDept(2);
System.out.println(employee);
} finally {
// 资源关闭,放在finally中确保一定会执行
sqlSession.close();
}
}
测试结果:
DEBUG 05-08 23:01:10,678 ==> Preparing: select e.id as eid, e.last_name, e.email, e.gender, d.id as did, d.dept_name from tbl_employee e LEFT JOIN tbl_department d on e.dept_id = d.id where e.id = ? (BaseJdbcLogger.java:145)
DEBUG 05-08 23:01:10,746 ==> Parameters: 2(Integer) (BaseJdbcLogger.java:145)
DEBUG 05-08 23:01:10,763 <== Total: 1 (BaseJdbcLogger.java:145)
Employee{id=2, lastName='BB', gender='0', email='bb@qq.com', department=Department{id=1, deptName='开发部', employeeList=null}}
(二)、分步查询
EmployeeMapper.java 接口方法:
Employee getByIdWithDeptStep(Integer id);
EmployeeMapper.xml sql映射文件:
<?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.wcg.mybatis.dao.EmployeeMapperPlus">
<!--
使用association进行分步查询:
1、先按照员工id查询员工信息
2、根据查询员工信息中的d_id值去部门表查出部门信息
3、部门设置到员工中;
-->
<resultMap id="employeeWithDeptStep" type="com.wcg.mybatis.entity.Employee">
<id column="id" property="id"></id>
<result column="last_name" property="lastName"></result>
<result column="gender" property="gender"></result>
<result column="email" property="email"></result>
<!-- association定义关联对象的封装规则
select:表明当前属性是调用select指定的方法查出的结果
column:指定将哪一列的值传给这个方法 注:如果多列情况使用{key=value...}的形式
流程:使用select指定的方法(传入column指定的这列参数的值)查出对象,并封装给property指定的属性
-->
<association property="department"
select="com.wcg.mybatis.dao.DepartmentMapper.getById"
column="dept_id">
</association>
</resultMap>
<select id="getByIdWithDeptStep" resultMap="employeeWithDeptStep">
select id,last_name,email,gender, dept_id from tbl_employee where id = #{id}
</select>
</mapper>
DepartmentMapper.xml sql映射文件:
<?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.wcg.mybatis.dao.DepartmentMapper">
<resultMap id="department" type="com.wcg.mybatis.entity.Department">
<id column="did" property="id"></id>
<result column="dept_name" property="deptName"></result>
</resultMap>
<select id="getById" resultMap="department">
SELECT id , dept_name FROM tbl_department WHERE id = #{id}
</select>
</mapper>
测试代码:
@Test
public void associationStepTest(){
// 获取 SqlSession 的实例 。SqlSession 完全包含了面向数据库执行 SQL 命令所需的所有方法。通过 SqlSession 实例来直接执行已映射的 SQL 语句
SqlSession sqlSession = null;
try {
sqlSession = sessionFactory.openSession();
// 通过获取接口代理对象来执行sql语句
EmployeeMapperPlus mapper = sqlSession.getMapper(EmployeeMapperPlus.class);
Employee employee = mapper.getByIdWithDeptStep(2);
System.out.println(employee);
} finally {
// 资源关闭,放在finally中确保一定会执行
sqlSession.close();
}
}
测试结果:
DEBUG 05-08 23:15:31,272 ==> Preparing: select id,last_name,email,gender, dept_id from tbl_employee where id = ? (BaseJdbcLogger.java:145)
DEBUG 05-08 23:15:31,339 ==> Parameters: 2(Integer) (BaseJdbcLogger.java:145)
DEBUG 05-08 23:15:31,370 ====> Preparing: SELECT id , dept_name FROM tbl_department WHERE id = ? (BaseJdbcLogger.java:145)
DEBUG 05-08 23:15:31,376 ====> Parameters: 1(Integer) (BaseJdbcLogger.java:145)
DEBUG 05-08 23:15:31,386 <==== Total: 1 (BaseJdbcLogger.java:145)
DEBUG 05-08 23:15:31,387 <== Total: 1 (BaseJdbcLogger.java:145)
Employee{id=2, lastName='BB', gender='0', email='bb@qq.com', department=Department{id=1, deptName='开发部', employeeList=null}}
四、collection定义关联对象封装结果集
(一)、普通查询
DepartmentMapper.java 接口方法:
Department getByIdWithEmp(Integer id);
DepartmentMapper.xml sql映射文件:
<?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.wcg.mybatis.dao.DepartmentMapper">
<!-- collection 结果集的方式:定义关联集合类型元素的封装规则 -->
<resultMap id="departmentWithEmp" type="com.wcg.mybatis.entity.Department">
<id column="did" property="id"></id>
<result column="dept_name" property="deptName"></result>
<!--
collection定义关联集合类型的属性的封装规则
ofType:指定集合里面元素的类型
-->
<collection property="employeeList" ofType="com.wcg.mybatis.entity.Employee">
<!-- 定义这个集合中元素的封装规则 -->
<id column="eid" property="id"></id>
<result column="last_name" property="lastName"></result>
<result column="gender" property="gender"></result>
<result column="email" property="email"></result>
</collection>
</resultMap>
<!-- collection 结果集的方式 -->
<select id="getByIdWithEmp" resultMap="departmentWithEmp">
SELECT
d.id as did, d.dept_name,
e.id as eid, e.last_name, e.email, e.gender
FROM
tbl_department d
LEFT JOIN tbl_employee e ON e.dept_id = d.id
WHERE d.id = #{id}
</select>
</mapper>
测试代码:
@Test
public void collectionTest(){
// 获取 SqlSession 的实例 。SqlSession 完全包含了面向数据库执行 SQL 命令所需的所有方法。通过 SqlSession 实例来直接执行已映射的 SQL 语句
SqlSession sqlSession = null;
try {
sqlSession = sessionFactory.openSession();
// 通过获取接口代理对象来执行sql语句
DepartmentMapper mapper = sqlSession.getMapper(DepartmentMapper.class);
Department department = mapper.getByIdWithEmp(1);
System.out.println(department);
} finally {
// 资源关闭,放在finally中确保一定会执行
sqlSession.close();
}
}
测试结果:
DEBUG 05-08 23:40:25,183 ==> Preparing: SELECT d.id as did, d.dept_name, e.id as eid, e.last_name, e.email, e.gender FROM tbl_department d LEFT JOIN tbl_employee e ON e.dept_id = d.id WHERE d.id = ? (BaseJdbcLogger.java:145)
DEBUG 05-08 23:40:25,291 ==> Parameters: 1(Integer) (BaseJdbcLogger.java:145)
DEBUG 05-08 23:40:25,333 <== Total: 2 (BaseJdbcLogger.java:145)
Department{id=1, deptName='开发部', employeeList=[Employee{id=2, lastName='BB', gender='0', email='bb@qq.com', department=null}, Employee{id=7, lastName='FF', gender='0', email='ff@qq.com', department=null}]}
(二)、分步查询
DepartmentMapper.java 接口方法:
Employee getByIdWithDeptStep(Integer id);
DepartmentMapper.xml sql映射文件:
<?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.wcg.mybatis.dao.DepartmentMapper">
<resultMap id="departmentWithEmpStep" type="com.wcg.mybatis.entity.Department">
<id column="id" property="id"></id>
<result column="dept_name" property="deptName"></result>
<collection property="employeeList"
ofType="com.wcg.mybatis.entity.Employee"
select="com.wcg.mybatis.dao.EmployeeMapperPlus.getEmpByDeptId"
column="id">
</collection>
</resultMap>
<!-- collection 结果集的方式 -->
<select id="getByIdWithEmpStep" resultMap="departmentWithEmpStep">
SELECT
d.id, d.dept_name
FROM
tbl_department d
WHERE d.id = #{id}
</select>
</mapper>
EmployeeMapper.xml sql映射文件:
<?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.wcg.mybatis.dao.EmployeeMapperPlus">
<!--
自定义某个javaBean的封装规则
type:自定义规则的Java类型
id:唯一id方便引用
-->
<resultMap id="employee" type="com.wcg.mybatis.entity.Employee">
<!--
指定主键列:
id定义主键会底层有优化;
column:字段
property:JavaBean属性
-->
<id column="id" property="id"></id>
<!-- 定义普通列封装规则 -->
<result column="last_name" property="lastName"></result>
<!-- 其他不指定的列会自动封装:我们只要写resultMap就把全部的映射规则都写上。 -->
<result column="gender" property="gender"></result>
<result column="email" property="email"></result>
</resultMap>
<select id="getEmpByDeptId" resultMap="employee">
select id,last_name,email,gender from tbl_employee where dept_id = #{id}
</select>
</mapper>
测试代码:
@Test
public void collectionStepTest(){
// 获取 SqlSession 的实例 。SqlSession 完全包含了面向数据库执行 SQL 命令所需的所有方法。通过 SqlSession 实例来直接执行已映射的 SQL 语句
SqlSession sqlSession = null;
try {
sqlSession = sessionFactory.openSession();
// 通过获取接口代理对象来执行sql语句
DepartmentMapper mapper = sqlSession.getMapper(DepartmentMapper.class);
Department department = mapper.getByIdWithEmpStep(1);
System.out.println(department);
} finally {
// 资源关闭,放在finally中确保一定会执行
sqlSession.close();
}
}
测试结果:
DEBUG 05-08 23:43:04,330 ==> Preparing: SELECT d.id, d.dept_name FROM tbl_department d WHERE d.id = ? (BaseJdbcLogger.java:145)
DEBUG 05-08 23:43:04,428 ==> Parameters: 1(Integer) (BaseJdbcLogger.java:145)
DEBUG 05-08 23:43:04,507 <== Total: 1 (BaseJdbcLogger.java:145)
DEBUG 05-08 23:43:04,509 ==> Preparing: select id,last_name,email,gender from tbl_employee where dept_id = ? (BaseJdbcLogger.java:145)
DEBUG 05-08 23:43:04,509 ==> Parameters: 1(Integer) (BaseJdbcLogger.java:145)
DEBUG 05-08 23:43:04,511 <== Total: 2 (BaseJdbcLogger.java:145)
Department{id=1, deptName='开发部', employeeList=[Employee{id=2, lastName='BB', gender='0', email='bb@qq.com', department=null}, Employee{id=7, lastName='FF', gender='0', email='ff@qq.com', department=null}]}
五、分步查询延迟加载(懒加载)
(1)什么是mybatis的懒加载
通俗的讲就是按需加载,我们需要什么的时候再去进行什么操作。而且先从单表查询,需要时再从关联表去关联查询,能大大提高数据库性能,
因为查询单表要比关联查询多张表速度要快。
在mybatis中,resultMap可以实现高级映射(使用association、collection实现一对一及一对多映射),association、collection具备延迟加载功能。
(二)、如何开启懒加载
在mybatis中开启延迟加载只要在全局配置文件中添加以下配置:
<settings>
<!-- 打开延迟加载的开关 -->
<setting name="lazyLoadingEnabled" value="true" />
<!-- 将积极加载改为消息加载即按需加载 -->
<setting name="aggressiveLazyLoading" value="false" />
<setting name="lazyLoadTriggerMethods" value=""/>
</settings>
mybatis全局配置:https://blog.youkuaiyun.com/qq_37776015/article/details/89892897
或者可以设置association或者collection中的fetchType属性来覆盖全局变量中的设置
- lazy:懒加载
- eager:急加载
根据上面的第四章:collection定义关联对象封装结果集的第二节:分步查询的测试代码如果没有开启懒加载的时候的测试结果为:
DEBUG 05-08 23:43:04,330 ==> Preparing: SELECT d.id, d.dept_name FROM tbl_department d WHERE d.id = ? (BaseJdbcLogger.java:145)
DEBUG 05-08 23:43:04,428 ==> Parameters: 1(Integer) (BaseJdbcLogger.java:145)
DEBUG 05-08 23:43:04,507 <== Total: 1 (BaseJdbcLogger.java:145)
DEBUG 05-08 23:43:04,509 ==> Preparing: select id,last_name,email,gender from tbl_employee where dept_id = ? (BaseJdbcLogger.java:145)
DEBUG 05-08 23:43:04,509 ==> Parameters: 1(Integer) (BaseJdbcLogger.java:145)
DEBUG 05-08 23:43:04,511 <== Total: 2 (BaseJdbcLogger.java:145)
Department{id=1, deptName='开发部', employeeList=[Employee{id=2, lastName='BB', gender='0', email='bb@qq.com', department=null}, Employee{id=7, lastName='FF', gender='0', email='ff@qq.com', department=null}]}
如果开启了懒加载:
DEBUG 05-08 23:53:01,207 ==> Preparing: SELECT d.id, d.dept_name FROM tbl_department d WHERE d.id = ? (BaseJdbcLogger.java:145)
DEBUG 05-08 23:53:01,278 ==> Parameters: 1(Integer) (BaseJdbcLogger.java:145)
DEBUG 05-08 23:53:01,362 <== Total: 1 (BaseJdbcLogger.java:145)
Department{id=1, deptName='开发部', employeeList=null}
我们会发现没有开启懒加载的时候执行了两条sql语句,而开启了懒加载的只执行了一条sql语句
把测试代码进行修改:
@Test
public void collectionStepTest(){
// 获取 SqlSession 的实例 。SqlSession 完全包含了面向数据库执行 SQL 命令所需的所有方法。通过 SqlSession 实例来直接执行已映射的 SQL 语句
SqlSession sqlSession = null;
try {
sqlSession = sessionFactory.openSession();
// 通过获取接口代理对象来执行sql语句
DepartmentMapper mapper = sqlSession.getMapper(DepartmentMapper.class);
Department department = mapper.getByIdWithEmpStep(1);
System.out.println(department);
System.out.println(department.getEmployeeList());
} finally {
// 资源关闭,放在finally中确保一定会执行
sqlSession.close();
}
}
测试结果:
DEBUG 05-09 00:03:48,057 ==> Preparing: SELECT d.id, d.dept_name FROM tbl_department d WHERE d.id = ? (BaseJdbcLogger.java:145)
DEBUG 05-09 00:03:48,164 ==> Parameters: 1(Integer) (BaseJdbcLogger.java:145)
DEBUG 05-09 00:03:48,222 <== Total: 1 (BaseJdbcLogger.java:145)
Department{id=1, deptName='开发部', employeeList=null}
DEBUG 05-09 00:03:48,225 ==> Preparing: select id,last_name,email,gender from tbl_employee where dept_id = ? (BaseJdbcLogger.java:145)
DEBUG 05-09 00:03:48,226 ==> Parameters: 1(Integer) (BaseJdbcLogger.java:145)
DEBUG 05-09 00:03:48,227 <== Total: 2 (BaseJdbcLogger.java:145)
[Employee{id=2, lastName='BB', gender='0', email='bb@qq.com', department=null}, Employee{id=7, lastName='FF', gender='0', email='ff@qq.com', department=null}]
通过查看测试结果可以发现,先从单表查询,需要时再从关联表去关联查询
注意:如果没有在全局配置中设置lazyLoadTriggerMethods属性的话,可能在调用toString方法时,使懒加载失效
六、鉴别器
概述:有时一个数据库查询语句会返回很多不同数据类型的结果集。鉴别器用于处理这种情况,还包括类的继承层次结构,其表现相当于Java中的switch语句。
下面情况具体测试代码:
EmployeeMapper.java 接口方法:
Employee getByIdWithDeptDiscriminator(Integer id);
EmployeeMapper.xml sql映射文件:
<?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.wcg.mybatis.dao.EmployeeMapperPlus">
<!-- =======================鉴别器============================ -->
<!-- <discriminator javaType=""></discriminator>
鉴别器:mybatis可以使用discriminator判断某列的值,然后根据某列的值改变封装行为
封装Employee:
如果查出的是女生:就把部门信息查询出来,否则不查询;
如果是男生,把last_name这一列的值赋值给email;
-->
<resultMap type="com.wcg.mybatis.entity.Employee" id="discriminatorEmployee">
<id column="id" property="id"/>
<result column="last_name" property="lastName"/>
<result column="email" property="email"/>
<result column="gender" property="gender"/>
<!--
column:指定判定的列名
javaType:列值对应的java类型 -->
<discriminator javaType="string" column="gender">
<!--女生 resultType:指定封装的结果类型;不能缺少。/resultMap-->
<case value="0" resultType="com.wcg.mybatis.entity.Employee">
<association property="dept"
select="com.wcg.mybatis.dao.DepartmentMapper.getById"
column="dept_id">
</association>
</case>
<!--男生 ;如果是男生,把last_name这一列的值赋值给email; -->
<case value="1" resultType="com.wcg.mybatis.entity.Employee">
<id column="id" property="id"/>
<result column="last_name" property="lastName"/>
<result column="last_name" property="email"/>
<result column="gender" property="gender"/>
</case>
</discriminator>
</resultMap>
<select id="getByIdWithDeptDiscriminator" resultMap="discriminatorEmployee">
select id,last_name,email,gender, dept_id from tbl_employee where id = #{id}
</select>
</mapper>
DepartmentMapper.xml sql映射文件:
<?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.wcg.mybatis.dao.DepartmentMapper">
<resultMap id="department" type="com.wcg.mybatis.entity.Department">
<id column="did" property="id"></id>
<result column="dept_name" property="deptName"></result>
</resultMap>
<select id="getById" resultMap="department">
SELECT id , dept_name FROM tbl_department WHERE id = #{id}
</select>
</mapper>
测试代码1:
数据: 2 BB 0 bb@qq.com 1
@Test
public void discriminatorTest(){
// 获取 SqlSession 的实例 。SqlSession 完全包含了面向数据库执行 SQL 命令所需的所有方法。通过 SqlSession 实例来直接执行已映射的 SQL 语句
SqlSession sqlSession = null;
try {
sqlSession = sessionFactory.openSession();
// 通过获取接口代理对象来执行sql语句
EmployeeMapperPlus mapper = sqlSession.getMapper(EmployeeMapperPlus.class);
Employee employee = mapper.getByIdWithDeptDiscriminator(2);
System.out.println(employee);
} finally {
// 资源关闭,放在finally中确保一定会执行
sqlSession.close();
}
}
测试结果1:
DEBUG 05-09 00:28:44,411 ==> Preparing: select id,last_name,email,gender, dept_id from tbl_employee where id = ? (BaseJdbcLogger.java:145)
DEBUG 05-09 00:28:44,499 ==> Parameters: 2(Integer) (BaseJdbcLogger.java:145)
DEBUG 05-09 00:28:44,563 ====> Preparing: SELECT id , dept_name FROM tbl_department WHERE id = ? (BaseJdbcLogger.java:145)
DEBUG 05-09 00:28:44,565 ====> Parameters: 1(Integer) (BaseJdbcLogger.java:145)
DEBUG 05-09 00:28:44,568 <==== Total: 1 (BaseJdbcLogger.java:145)
DEBUG 05-09 00:28:44,568 <== Total: 1 (BaseJdbcLogger.java:145)
Employee{id=2, lastName='BB', gender='0', email='bb@qq.com', department=Department{id=1, deptName='开发部', employeeList=null}}
得出结论:该gender为0,走了分支一查询出了部门信息
测试代码2:
数据:3 CC 1 cc@qq.com 2
@Test
public void discriminatorTest(){
// 获取 SqlSession 的实例 。SqlSession 完全包含了面向数据库执行 SQL 命令所需的所有方法。通过 SqlSession 实例来直接执行已映射的 SQL 语句
SqlSession sqlSession = null;
try {
sqlSession = sessionFactory.openSession();
// 通过获取接口代理对象来执行sql语句
EmployeeMapperPlus mapper = sqlSession.getMapper(EmployeeMapperPlus.class);
Employee employee = mapper.getByIdWithDeptDiscriminator(3);
System.out.println(employee);
} finally {
// 资源关闭,放在finally中确保一定会执行
sqlSession.close();
}
}
测试结果2:
DEBUG 05-09 00:32:43,805 ==> Preparing: select id,last_name,email,gender, dept_id from tbl_employee where id = ? (BaseJdbcLogger.java:145)
DEBUG 05-09 00:32:43,868 ==> Parameters: 3(Integer) (BaseJdbcLogger.java:145)
DEBUG 05-09 00:32:43,890 <== Total: 1 (BaseJdbcLogger.java:145)
Employee{id=3, lastName='CC', gender='1', email='CC', department=null}
得出结论:该gender为1,走了分支二把last_name的值赋给了email