MyBatis分步查询的延迟加载
- 延迟加载的概念只存在于分步查询时;
- 延迟加载的本质是为第一步查询返回的Java Bean创建了一个代理对象;
- 延迟加载的全局设置有两个:
- lazyLoadingEnabled,作用为设置select语句的默认延迟加载是否开启;
aggressiveLazyLoading,对于开启了延迟加载的select作用如下:
- 值为true时,假设select返回的Java Bean为xxx,那么获取任何xxx属性的动作都会导致resultMap中定义的所有关联查询马上执行;
- 值为false时,假设yyy为xxx的一个属性,由关联查询获取,那么只有在yyy的某一属性被使用时,获取yyy的关联查询才会执行
- 延迟加载针对单个查询的具体设置为resultMap的 fetchType属性;
- 全局设置lazyLoadingEnabled和具体设置fetchType的关系如下:
- 如果设置了resultMap的 fetchType属性,那么全局设置lazyLoadingEnabled便不再对该select生效,是否延迟加载要以fetchType属性为准;
- 如果select的resultMap没有设置 fetchType属性,那么该select会采用lazyLoadingEnabled的设置;
- aggressiveLazyLoading只对延迟加载的select生效
演示如下
需要注意的是,一下演示在DEBUG模式下不成立,均为RUN模式;DEBUG模式下(IDEA环境)MyBatis不会延迟加载
E-R图:一个City隶属于一个Country,同时一个City包含多个Address
实体类:CityPlusPlus中包含一个Country和多个Address
CityPlusPlus
public class CityPlusPlus {
private Long id;
private String name;
private Long countryId;
private Date lastUpdate;
private Country country;
private List<Address> addressList;
}
Country
public class Country {
Long id;
String name;
Date lastUpdate;
}
Address
public class Address {
Long addressId;
String address;
String address2;
String district;
String postalCode;
String phone;
Long cityId;
Location location;
Date lastUpdate;
}
lazyLoadingEnabled和aggressiveLazyLoading均为true,fetchType不设置
<?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="canger.study.chapter04.mapper.CityPlusPlusMapper"> <resultMap id="cityPlusPlusResultMap" type="canger.study.chapter04.bean.CityPlusPlus">
<id column="city_id" property="id"/>
<result column="city" property="name"/>
<result column="country_id" property="countryId"/>
<result column="last_update" property="lastUpdate"/>
<association property="country"
select="canger.study.chapter04.mapper.CountryMapper.selectCountryById"
column="country_id"/>
<association property="addressList"
select="canger.study.chapter04.mapper.AddressMapper.selectAddressesByCityId"
column="city_id"/>
</resultMap> <select id="selectCityPlusPlusById" resultMap="cityPlusPlusResultMap">
select *
from city
where city_id=#{id}
</select>
</mapper>
<settings>
<setting name="mapUnderscoreToCamelCase" value="true"/>
<setting name="lazyLoadingEnabled" value="true"/>
<setting name="aggressiveLazyLoading" value="true"/>
</settings>
测试代码如下:
@Test
public void testCityPlusPlusMapper(){
SqlSessionFactory sqlSessionFactory = SqlSessionFactoryUtil.initSqlSessionFactory();
SqlSession sqlSession = null; try {
sqlSession = sqlSessionFactory.openSession();
CityPlusPlusMapper mapper = sqlSession.getMapper(CityPlusPlusMapper.class);
System.out.println("************开始主动查询**************");
CityPlusPlus cityPlusPlus = mapper.selectCityPlusPlusById(42L);
System.out.println("*************主动查询结束*************");
System.out.println(cityPlusPlus.getName());
System.out.println("*************Step2*************");
System.out.println(cityPlusPlus.getCountry());
System.out.println("**************Step3************");
System.out.println(cityPlusPlus.getAddressList());
System.out.println();
System.out.println();
sqlSession.commit();
} catch (Exception e) {
e.printStackTrace();
sqlSession.rollback();
} finally {
sqlSession.close();
}
}
日志输出如下,可以看到,当调用 cityPlusPlus.getName() 时,两个关联查询均马上执行
************开始主动查询**************
[DEBUG] 2018-11-21 23:37:12,307(300) --> [main] org.apache.ibatis.transaction.jdbc.JdbcTransaction.openConnection(JdbcTransaction.java:137): Opening JDBC Connection
[DEBUG] 2018-11-21 23:37:12,552(545) --> [main] org.apache.ibatis.datasource.pooled.PooledDataSource.popConnection(PooledDataSource.java:406): Created connection 1514160588.
[DEBUG] 2018-11-21 23:37:12,553(546) --> [main] org.apache.ibatis.transaction.jdbc.JdbcTransaction.setDesiredAutoCommit(JdbcTransaction.java:101): Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@5a4041cc]
[DEBUG] 2018-11-21 23:37:12,555(548) --> [main] org.apache.ibatis.logging.jdbc.BaseJdbcLogger.debug(BaseJdbcLogger.java:159): ==> Preparing: select * from city where city_id=?
[DEBUG] 2018-11-21 23:37:12,575(568) --> [main] org.apache.ibatis.logging.jdbc.BaseJdbcLogger.debug(BaseJdbcLogger.java:159): ==> Parameters: 42(Long)
[DEBUG] 2018-11-21 23:37:12,631(624) --> [main] org.apache.ibatis.logging.jdbc.BaseJdbcLogger.debug(BaseJdbcLogger.java:159): <== Total: 1
*************主动查询结束*************
[DEBUG] 2018-11-21 23:37:12,632(625) --> [main] org.apache.ibatis.logging.jdbc.BaseJdbcLogger.debug(BaseJdbcLogger.java:159): ==> Preparing: select * from country where country_id=?
[DEBUG] 2018-11-21 23:37:12,637(630) --> [main] org.apache.ibatis.logging.jdbc.BaseJdbcLogger.debug(BaseJdbcLogger.java:159): ==> Parameters: 103(Integer)
[DEBUG] 2018-11-21 23:37:12,640(633) --> [main] org.apache.ibatis.logging.jdbc.BaseJdbcLogger.debug(BaseJdbcLogger.java:159): <== Total: 1
[DEBUG] 2018-11-21 23:37:12,641(634) --> [main] org.apache.ibatis.logging.jdbc.BaseJdbcLogger.debug(BaseJdbcLogger.java:159): ==> Preparing: select address_id,address,address2,district,city_id,postal_code,phone,astext(location) as location,last_update from address where city_id=?
[DEBUG] 2018-11-21 23:37:12,641(634) --> [main] org.apache.ibatis.logging.jdbc.BaseJdbcLogger.debug(BaseJdbcLogger.java:159): ==> Parameters: 42(Integer)
[DEBUG] 2018-11-21 23:37:12,651(644) --> [main] org.apache.ibatis.logging.jdbc.BaseJdbcLogger.debug(BaseJdbcLogger.java:159): <== Total: 2
Aurora
*************Step2*************
Country{id=103, name='United States', lastUpdate=Wed Feb 15 04:44:00 CST 2006}
**************Step3************
[Address{addressId=335, address='587 Benguela Manor', address2='', district='Illinois', postalCode='91590', phone='165450987037', cityId=42, location=POINT(-88.3200762 41.760583), lastUpdate=Thu Sep 25 22:33:44 CST 2014}, Address{addressId=543, address='43 Vilnius Manor', address2='', district='Colorado', postalCode='79814', phone='484500282381', cityId=42, location=POINT(-104.8319273 39.729439), lastUpdate=Thu Sep 25 22:33:44 CST 2014}]
lazyLoadingEnabled为true和aggressiveLazyLoading为false,fetchType不设置
<settings>
<setting name="mapUnderscoreToCamelCase" value="true"/>
<setting name="lazyLoadingEnabled" value="true"/>
<setting name="aggressiveLazyLoading" value="false"/>
</settings>
输出日志,可以看到:
- 当调用cityPlusPlus.getCountry() 时,第一个关联查询执行
- 当调用cityPlusPlus.getAddressList()时,第二个关联查询执行
************开始主动查询**************
[DEBUG] 2018-11-21 23:56:04,599(286) --> [main] org.apache.ibatis.transaction.jdbc.JdbcTransaction.openConnection(JdbcTransaction.java:137): Opening JDBC Connection
[DEBUG] 2018-11-21 23:56:04,829(516) --> [main] org.apache.ibatis.datasource.pooled.PooledDataSource.popConnection(PooledDataSource.java:406): Created connection 1514160588.
[DEBUG] 2018-11-21 23:56:04,830(517) --> [main] org.apache.ibatis.transaction.jdbc.JdbcTransaction.setDesiredAutoCommit(JdbcTransaction.java:101): Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@5a4041cc]
[DEBUG] 2018-11-21 23:56:04,844(531) --> [main] org.apache.ibatis.logging.jdbc.BaseJdbcLogger.debug(BaseJdbcLogger.java:159): ==> Preparing: select * from city where city_id=?
[DEBUG] 2018-11-21 23:56:04,865(552) --> [main] org.apache.ibatis.logging.jdbc.BaseJdbcLogger.debug(BaseJdbcLogger.java:159): ==> Parameters: 42(Long)
[DEBUG] 2018-11-21 23:56:04,941(628) --> [main] org.apache.ibatis.logging.jdbc.BaseJdbcLogger.debug(BaseJdbcLogger.java:159): <== Total: 1
*************主动查询结束*************
Aurora
*************Step2*************
[DEBUG] 2018-11-21 23:56:04,942(629) --> [main] org.apache.ibatis.logging.jdbc.BaseJdbcLogger.debug(BaseJdbcLogger.java:159): ==> Preparing: select * from country where country_id=?
[DEBUG] 2018-11-21 23:56:04,943(630) --> [main] org.apache.ibatis.logging.jdbc.BaseJdbcLogger.debug(BaseJdbcLogger.java:159): ==> Parameters: 103(Integer)
[DEBUG] 2018-11-21 23:56:04,956(643) --> [main] org.apache.ibatis.logging.jdbc.BaseJdbcLogger.debug(BaseJdbcLogger.java:159): <== Total: 1
Country{id=103, name='United States', lastUpdate=Wed Feb 15 04:44:00 CST 2006}
**************Step3************
[DEBUG] 2018-11-21 23:56:04,961(648) --> [main] org.apache.ibatis.logging.jdbc.BaseJdbcLogger.debug(BaseJdbcLogger.java:159): ==> Preparing: select address_id,address,address2,district,city_id,postal_code,phone,astext(location) as location,last_update from address where city_id=?
[DEBUG] 2018-11-21 23:56:04,961(648) --> [main] org.apache.ibatis.logging.jdbc.BaseJdbcLogger.debug(BaseJdbcLogger.java:159): ==> Parameters: 42(Integer)
[DEBUG] 2018-11-21 23:56:04,971(658) --> [main] org.apache.ibatis.logging.jdbc.BaseJdbcLogger.debug(BaseJdbcLogger.java:159): <== Total: 2
[Address{addressId=335, address='587 Benguela Manor', address2='', district='Illinois', postalCode='91590', phone='165450987037', cityId=42, location=POINT(-88.3200762 41.760583), lastUpdate=Thu Sep 25 22:33:44 CST 2014}, Address{addressId=543, address='43 Vilnius Manor', address2='', district='Colorado', postalCode='79814', phone='484500282381', cityId=42, location=POINT(-104.8319273 39.729439), lastUpdate=Thu Sep 25 22:33:44 CST 2014}]
MyBatis分步查询的延迟加载的更多相关文章
- mybatis分步查询与延迟加载
1.分步查询 先查询用户的部门 部门Mapper.xml <resultMap id="rMap" type="com.yunqing.mybatis.bean.D ...
- MyBatis学习——分步查询与延迟加载
声明:面试是遇到延迟加载问题,在网页搜索到此篇文章,感觉很有帮助,留此学习之用! 一.分步查询 分步查询通常应用于关联表查询,如:电商平台,查询订单信息时需要查询部分的用户信息:OA系统查询个人信息时 ...
- Mybatis3.1-[tp_34-35]-_映射文件_select_resultMap关联查询_collection定义关联集合封装规则_collection分步查询_延迟加载
笔记要点出错分析与总结工程组织 1.定义接口 interface DepartmentMapper package com.dao; import com.bean.Department; publi ...
- Mybatis3.1-[tp_32-33]-_映射文件_select_resultMap关联查询_association分步查询_延迟加载
笔记要点出错分析与总结 工程组织 1.定义接口 DepartmentMapper package com.dao; import com.bean.Department; public interfa ...
- MyBatis联合查询和使用association 进行分步式查询
查询Emp的同时,查出emp对应的部门Department 方法1:联合查询,使用级联属性封装结果集 <!-- 联合查询,使用级联属性封装结果集 type:要自定义规则的javaBean类型 i ...
- mybatis使用associaton进行分步查询
Employee类 public class Employee { private Integer id; private String lastName; private String email; ...
- Java框架之MyBatis 06-全局配置-mapper映射-分步查询
MyBatis MyBatis是Apache的一个开源项目iBatis, iBatis一词来源于“internet”和“abatis”的组合,是一个基于Java的持久层框架. iBatis 提供的持 ...
- Mybatis源码分析--关联表查询及延迟加载原理(二)
在上一篇博客Mybatis源码分析--关联表查询及延迟加载(一)中我们简单介绍了Mybatis的延迟加载的编程,接下来我们通过分析源码来分析一下Mybatis延迟加载的实现原理. 其实简单来说Myba ...
- mybatis基础系列(四)——关联查询、延迟加载、一级缓存与二级缓存
关本文是Mybatis基础系列的第四篇文章,点击下面链接可以查看前面的文章: mybatis基础系列(三)——动态sql mybatis基础系列(二)——基础语法.别名.输入映射.输出映射 mybat ...
随机推荐
- mysql数据库创建和权限分配
查询安装路径: whereis mysql连接mysql: mysql -u root -p第一步:创建用户CREATE USER 'claim_prod'@'%' IDENTIFIED BY 'Pa ...
- poj 3169 Layout(线性差分约束,spfa:跑最短路+判断负环)
Layout Time Limit: 1000MS Memory Limit: 65536K Total Submissions: 15349 Accepted: 7379 Descripti ...
- 使用git初始化本地仓库并提交到远程分支
创建本地文件并提交到github远程分支,步骤如下: 1.通过github创建repository,本例中repository名称为maven_demo,工程为maven + spring + myb ...
- day62
一.组件 组件都具有模板,template new Vue()创建的是根组件 组件与实例一一对应,创建一个实例就是创建了一个组件,同理创建一个组件就相当于创建了一个实例 根组件的挂载点一般就是根组件的 ...
- [Usaco2005 Open]Disease Manangement 疾病管理 BZOJ1688
分析: 这个题的状压DP还是比较裸的,考虑将疾病状压,得到DP方程:F[S]为疾病状态为S时的最多奶牛数量,F[S]=max{f[s]+1}; 记得预处理出每个状态下疾病数是多少... 附上代码: # ...
- 关于docker构建镜像
今天正好看到这一块了,记录一下,希望可以帮助到大家. 构建Dockerfile 先来看一个示例: --------------------------------------------------- ...
- bundle install 安装的 gem 提示 cannot load such file
/usr/local/lib/ruby/site_ruby/2.1.0/rubygems/core_ext/kernel_require.rb:54:in `require': cannot load ...
- 实现MD5的加密和解密
加密代码 public static string Encrypt(string Text, string sKey) { DESCryptoServiceProvider des = new DES ...
- tf tensor 输出
在学习TensorFlow的过程中,我们需要知道某个tensor的值是什么,这个很重要,尤其是在debug的时候.也许你会说,这个很容易啊,直接print就可以了.其实不然,print只能打印输出sh ...
- [THUSC2017]巧克力[斯坦纳树、随机化]
题意 题目链接 分析 对于第一问,如果颜色数量比较少的话可以 \(\binom{cnt}{k}\) 枚举最终连通块中的 \(k\) 种颜色,然后利用斯坦纳树求解. 如果颜色比较多,考虑将所有的颜色重新 ...