通过前面的学习,我们已经掌握了 Mybatis 中一对一,一对多,多对多关系的配置及实现,可以实现对象的关联查询。
我们昨天在配置emp和dept关联查询时,不管部门信息是否有使用到,都会把部门信息查询出来;我们希望查询员工信息时,暂时不查询部门信息,等到使用到部门信息的时候,再发送SQL语句查询部门相关信息,这样可以大大提高数据库的性能;
延迟加载,顾名思义就是在需要用到数据时才进行加载,不需要用到数据时就不加载数据。延迟加载也称懒加载;
drop table if exists dept;
CREATE TABLE `dept` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '部门名称',
`location` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '部门地址',
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 1 ;
INSERT INTO `dept` VALUES (1, '研发部', '中国台湾');
INSERT INTO `dept` VALUES (2, '市场部', '中国香港');
INSERT INTO `dept` VALUES (3, '行政部', '中国钓鱼岛');
INSERT INTO `dept` VALUES (4, '销售部', '中国江西');
drop table if exists emp;
CREATE TABLE `emp` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '员工姓名',
`age` int(11) NULL DEFAULT NULL COMMENT '员工年龄',
`addr` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '籍贯',
`salary` decimal(10, 2) NULL DEFAULT NULL COMMENT '薪资',
`dept_id` int(11) NULL DEFAULT NULL COMMENT '部门id',
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
INSERT INTO `emp` VALUES (1, '张三', 20, '广西来宾', 7600.00, 1);
INSERT INTO `emp` VALUES (2, '李四', 22, '浙江绍兴', 6800.00, 4);
INSERT INTO `emp` VALUES (3, '小明', 25, '广东云浮', 6600.00, 2);
INSERT INTO `emp` VALUES (4, '小红', 23, '河南信阳', 7000.00, 3);
INSERT INTO `emp` VALUES (5, '张明', 25, '山东临沂', 8000.00, 1);
<dependencies>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>3.5.5version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>5.1.47version>
dependency>
<dependency>
<groupId>log4jgroupId>
<artifactId>log4jartifactId>
<version>1.2.17version>
dependency>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>4.12version>
dependency>
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
<version>1.18.12version>
dependency>
dependencies>
DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
<setting name="lazyLoadingEnabled" value="true"/>
settings>
<typeAliases>
<package name="com.dfbz.entity"/>
typeAliases>
<environments default="dev">
<environment id="dev">
<transactionManager type="JDBC">transactionManager>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver">property>
<property name="url" value="jdbc:mysql://localhost:3306/test?characterEncoding=UTF8">property>
<property name="username" value="root">property>
<property name="password" value="admin">property>
dataSource>
environment>
environments>
<mappers>
<package name="com.dfbz.dao"/>
mappers>
configuration>
package com.dfbz.entity;
import lombok.Data;
/**
* @author lscl
* @version 1.0
* @intro:
*/
@Data
public class Emp {
private Integer id;
private String name;
private Integer age;
private String addr;
private Double salary;
// 一个员工属于一个部门
private Dept dept;
}
package com.dfbz.entity;
import lombok.Data;
import java.util.List;
/**
* @author lscl
* @version 1.0
* @intro:
*/
@Data
public class Dept {
private Integer id;
private String name;
private String location;
// 一个部门下有多个员工
private List<Emp> empList;
}
package com.dfbz.dao;
import com.dfbz.entity.Emp;
import org.apache.ibatis.annotations.Param;
import java.util.List;
import java.util.Set;
/**
* @author lscl
* @version 1.0
* @intro:
*/
public interface EmpDao {
}
package com.dfbz.dao;
import com.dfbz.entity.Dept;
import java.util.List;
/**
* @author lscl
* @version 1.0
* @intro:
*/
public interface DeptDao {
}
DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.dfbz.dao.EmpDao">
mapper>
DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.dfbz.dao.DeptDao">
mapper>
搭建工程如下:
SQL语句:
-- 一对一延迟加载
-- 需求:查询员工,同时也要显示部门。但部门信息是再用到的时候再查询.
-- 实现过程:
-- 1) 查询员工
SELECT * FROM emp;
-- 3) 使用Dept对象数据时候,查询部门
SELECT * FROM dept WHERE id=1;
public interface EmpDao {
List<Emp> findAll();
}
public interface DeptDao {
Dept findById(Integer id);
}
DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.dfbz.dao.DeptDao">
<select id="findById" resultType="dept">
select * from dept where id=#{id}
select>
mapper>
DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.dfbz.dao.EmpDao">
<resultMap id="empResultMap" type="emp">
<id column="id" property="id">id>
<result column="name" property="name">result>
<result column="addr" property="addr">result>
<result column="salary" property="salary">result>
<association property="dept" javaType="com.dfbz.entity.Dept"
column="dept_id" select="com.dfbz.dao.DeptDao.findById">
<id column="id" property="id">id>
<result column="deptName" property="name">result>
<result column="location" property="location">result>
association>
resultMap>
<select id="findAll" resultMap="empResultMap">
select * from emp
select>
mapper>
Tips:将SQL语句拆分为两条后,查询的列和实体类属性名一致时可以不用手动映射;
<setting name="lazyLoadingEnabled" value="true"/>
// 一对一延迟加载
@Test
public void test1() {
List<Emp> empList = empDao.findAll();
for (Emp emp : empList) {
System.out.println(emp.getId()+"---"+emp.getName());
}
}
执行测试单元,观察日志:
我们发现,我们没有使用到部门相关的信息,但是部门依旧被查询到了,好像没有实现延迟加载的功能;这是为什么?
在MyBatis中,默认的延迟加载功能被关闭了,我们需要在全局配置文件中,开启延迟加载功能;
<setting name="lazyLoadingEnabled" value="true"/>
再次执行测试,观察日志,发现部门信息如果没有使用的话,则不会去查询部门;
我们也可以针对单个SQL语句的懒加载设置;
<resultMap id="empAllMap" type="com.dfbz.entity.Emp">
<id column="id" property="id">id>
<result column="name" property="name">result>
<result column="age" property="age">result>
<result column="addr" property="addr">result>
<result column="salary" property="salary">result>
<association property="dept" javaType="com.dfbz.entity.Dept"
select="com.dfbz.dao.DeptDao.findById" column="dept_id">
association>
resultMap>
<select id="findAll" resultMap="empAllMap">
select * from emp
select>
Tips:当全局配置文件和mapper文件设置的加载方式不一样时以SQL语句上的配置为准
SQL语句:
-- 一对多延迟加载
-- 1) 查询部门
SELECT * FROM dept;
-- 2) 使用到员工信息之后再去查询员工信息
SELECT * FROM emp WHERE dept_id=1;
List<Dept> findAll();
List<Emp> findByDeptId(Integer deptId);
<select id="findByDeptId" resultType="emp">
select * from emp where dept_id=#{deptId}
select>
<resultMap id="deptResultMap" type="dept">
<id column="id" property="id">id>
<result column="name" property="name">result>
<result column="location" property="location">result>
<collection property="empList" ofType="com.dfbz.entity.Emp"
column="id" fetchType="lazy"
select="com.dfbz.dao.EmpDao.findByDeptId">
<result column="name" property="name">result>
<result column="addr" property="addr">result>
<result column="salary" property="salary">result>
collection>
resultMap>
<select id="findAll" resultMap="deptResultMap">
select * from dept;
select>
// 一对多延迟加载
@Test
public void test2() {
List<Dept> deptList = deptDao.findAll();
for (Dept dept : deptList) {
System.out.println(dept.getId()+"---"+dept.getName());
}
}