1、概述
延迟加载,就是在需要用到数据时才进行加载,不需要用到数据时就不加载数据。延迟加载也称懒加载。
一般,“一对多”、“多对多”的情况下,会采用延迟加载,即先从一个表中查询,再去从关联的表中查询数据。
只有嵌套查询,才能实现延迟加载。
2、全局延迟加载
- 全局延迟加载,在 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>
······
<settings>
······
<setting name="aggressiveLazyLoading" value="false"/>
<setting name="lazyLoadingEnabled" value="false"/>
<setting name="lazyLoadTriggerMethods" value="equals,clone,hashCode,toString"/>
······
</settings>
······
</configuration>
lazyLoadingEnabled
:“开启延迟加载”。有效值true
或false
,默认值为false
。为true
时,说明开启了全局的延迟加载。
aggressiveLazyLoading
:“激进的延迟加载”。有效值true
或false
,默认值为false
(在3.4.1
及之前的版本中默认为true
)。一旦配置为true
,只要对这个对象(查询出的对象)的任意操作,都将完整加载整个类的所有属性即执行级联的SQL语句。
lazyLoadTriggerMethods
:“触发加载的方法”。有效值为用逗号分隔的方法列表,默认值为equals,clone,hashCode,toString
。这个配置的含义是“除了直接使用的时候进行加载以外,哪些方法还会触发加载”。
- 案例一:
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
// 这里不用 @ToString,因为这个注解生成的 toString() 方法,会使用 for 循环去遍历 List
@NoArgsConstructor
@AllArgsConstructor
@Data
public class User {
private Integer id;
private String nickname;
private String phoneNumber;
private List<Order> orderList;
@Override
public String toString() {
return "User{" +
"id=" + id +
", nickname='" + nickname + '\'' +
", phoneNumber='" + phoneNumber + '\'' +
", orderList=" + orderList +
'}';
}
}
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
import java.math.BigDecimal;
@NoArgsConstructor
@AllArgsConstructor
@Data
@ToString
public class Order {
private Integer id;
private BigDecimal account;
}
import com.yscyber.mybatis.five.pojo.Order;
import java.util.List;
public interface OrderRepo {
List<Order> listOrdersByUserId(Integer userId);
}
import com.yscyber.mybatis.five.pojo.User;
public interface UserRepo {
User getUserById(Integer id);
}
<?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.yscyber.mybatis.five.repo.OrderRepo">
<resultMap id="orderResultMap" type="Order">
<id property="id" column="order_id"/>
<result property="account" column="order_account"/>
</resultMap>
<select id="listOrdersByUserId" parameterType="int" resultMap="orderResultMap">
SELECT order_id, order_account
FROM lg_order
WHERE order_user_id=#{userId}
</select>
</mapper>
<?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.yscyber.mybatis.five.repo.UserRepo">
<resultMap id="userResultMap" type="User">
<id property="id" column="user_id"/>
<result property="nickname" column="user_nickname"/>
<result property="phoneNumber" column="user_phone_number"/>
<!--
将查询出的 column="user_id" 作为 listOrdersByUserId 参数
-->
<collection property="orderList" ofType="Order" select="com.yscyber.mybatis.five.repo.OrderRepo.listOrdersByUserId" column="user_id">
<id property="id" column="order_id"/>
<result property="account" column="order_account"/>
</collection>
</resultMap>
<select id="getUserById" parameterType="int" resultMap="userResultMap">
SELECT user_id, user_nickname, user_phone_number
FROM lg_user
WHERE user_id=#{id}
</select>
</mapper>
<?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>
<properties resource="jdbc.properties"/>
<settings>
<setting name="mapUnderscoreToCamelCase" value="true"/>
<setting name="lazyLoadingEnabled" value="true"/>
<setting name="aggressiveLazyLoading" value="false"/>
<!-- 为了能够更直观的看到“延迟加载”,将“触发的方法”设置为空,否则打印输出也触发加载 -->
<setting name="lazyLoadTriggerMethods" value=""/>
</settings>
<typeAliases>
<package name="com.yscyber.mybatis.five.pojo"/>
</typeAliases>
<plugins>
<plugin interceptor="com.github.pagehelper.PageInterceptor">
<property name="helperDialect" value="mysql"/>
</plugin>
</plugins>
<environments default="dev">
<!-- 配置数据源 -->
<environment id="dev">
<transactionManager type="JDBC" />
<dataSource type="POOLED">
<property name="driver" value="${jdbc_driver}"/>
<property name="url" value="${jdbc_url}"/>
<property name="username" value="${jdbc_username}"/>
<property name="password" value="${jdbc_password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<package name="com.yscyber.mybatis.five.repo"/>
</mappers>
</configuration>
@Test
public void test1() throws IOException {
InputStream ris = Resources.getResourceAsStream("mybatis.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(ris);
SqlSession sqlSession = sqlSessionFactory.openSession();
UserRepo userRepo = sqlSession.getMapper(UserRepo.class);
User user = userRepo.getUserById(1);
System.out.println(user); // User{id=1, nickname='张三', phoneNumber='1820000000', orderList=null}
List<Order> orderList = user.getOrderList(); // 执行此语句时,才执行子查询
for (Order order : orderList) {
System.out.println(order);
}
sqlSession.close();
}
- 案例二:
aggressiveLazyLoading
为true
时,查询出的对象只要进行任何操作,立即触发加载
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
@NoArgsConstructor
@AllArgsConstructor
@Data
public class User {
private Integer id;
private String nickname;
private String phoneNumber;
private List<Order> orderList;
@Override
public String toString() {
return "User{" +
"id=" + id +
", nickname='" + nickname + '\'' +
", phoneNumber='" + phoneNumber + '\'' +
", orderList=" + orderList +
'}';
}
}
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
import java.math.BigDecimal;
@NoArgsConstructor
@AllArgsConstructor
@Data
@ToString
public class Order {
private Integer id;
private BigDecimal account;
}
import com.yscyber.mybatis.five.pojo.Order;
import java.util.List;
public interface OrderRepo {
List<Order> listOrdersByUserId(Integer userId);
}
import com.yscyber.mybatis.five.pojo.User;
public interface UserRepo {
User getUserById(Integer id);
}
<?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.yscyber.mybatis.five.repo.OrderRepo">
<resultMap id="orderResultMap" type="Order">
<id property="id" column="order_id"/>
<result property="account" column="order_account"/>
</resultMap>
<select id="listOrdersByUserId" parameterType="int" resultMap="orderResultMap">
SELECT order_id, order_account
FROM lg_order
WHERE order_user_id=#{userId}
</select>
</mapper>
<?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.yscyber.mybatis.five.repo.UserRepo">
<resultMap id="userResultMap" type="User">
<id property="id" column="user_id"/>
<result property="nickname" column="user_nickname"/>
<result property="phoneNumber" column="user_phone_number"/>
<!--
将查询出的 column="user_id" 作为 listOrdersByUserId 参数
-->
<collection property="orderList" ofType="Order" select="com.yscyber.mybatis.five.repo.OrderRepo.listOrdersByUserId" column="user_id">
<id property="id" column="order_id"/>
<result property="account" column="order_account"/>
</collection>
</resultMap>
<select id="getUserById" parameterType="int" resultMap="userResultMap">
SELECT user_id, user_nickname, user_phone_number
FROM lg_user
WHERE user_id=#{id}
</select>
</mapper>
<?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>
<properties resource="jdbc.properties"/>
<settings>
<setting name="mapUnderscoreToCamelCase" value="true"/>
<setting name="lazyLoadingEnabled" value="true"/>
<setting name="aggressiveLazyLoading" value="true"/>
<setting name="lazyLoadTriggerMethods" value=""/>
</settings>
<typeAliases>
<package name="com.yscyber.mybatis.five.pojo"/>
</typeAliases>
<plugins>
<plugin interceptor="com.github.pagehelper.PageInterceptor">
<property name="helperDialect" value="mysql"/>
</plugin>
</plugins>
<environments default="dev">
<!-- 配置数据源 -->
<environment id="dev">
<transactionManager type="JDBC" />
<dataSource type="POOLED">
<property name="driver" value="${jdbc_driver}"/>
<property name="url" value="${jdbc_url}"/>
<property name="username" value="${jdbc_username}"/>
<property name="password" value="${jdbc_password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<package name="com.yscyber.mybatis.five.repo"/>
</mappers>
</configuration>
@Test
public void test1() throws IOException {
InputStream ris = Resources.getResourceAsStream("mybatis.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(ris);
SqlSession sqlSession = sqlSessionFactory.openSession();
UserRepo userRepo = sqlSession.getMapper(UserRepo.class);
User user = userRepo.getUserById(1);
System.out.println(user); // 由于“打印输出”相当于调用了对象的 toString() 方法,所以在 aggressiveLazyLoading 为 true 的情况下,触发加载
sqlSession.close();
}
3、局部延迟加载
局部配置的优先级高于全局配置,如果局部要求非延迟(映射配置文件中配置),全局要求延迟(核心配置文件中配置),以局部为准。
局部延迟加载,配置在映射文件中。
fetchType="lazy"
表示延迟加载,fetchType="eager"
表示非延迟加载
<?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.yscyber.mybatis.five.repo.UserRepo">
<resultMap id="userResultMap" type="User">
<id property="id" column="user_id"/>
<result property="nickname" column="user_nickname"/>
<result property="phoneNumber" column="user_phone_number"/>
<!--
将查询出的 column="user_id" 作为 listOrdersByUserId 参数
-->
<collection property="orderList" ofType="Order" select="com.yscyber.mybatis.five.repo.OrderRepo.listOrdersByUserId" column="user_id" fetchType="lazy">
<id property="id" column="order_id"/>
<result property="account" column="order_account"/>
</collection>
</resultMap>
<select id="getUserById" parameterType="int" resultMap="userResultMap">
SELECT user_id, user_nickname, user_phone_number
FROM lg_user
WHERE user_id=#{id}
</select>
</mapper>