11-20 程宗武
11-20 Mybatis03
1.Mybatis延迟加载
延迟加载: 就是在需要用到数据时才进行加载,不需要用到数据时就不加载数据。延迟加载也称懒加载.
好处: 先从单表查询,需要时再从关联表去关联查询,大大提高数据库性能,因为查询单表要比关联查询多张 表速度要快。
坏处: 因为只有当需要用到数据时,才会进行数据库查询,这样在大批量数据查询时,因为查询工作也要消耗 时间,所以可能造成用户等待时间变长,造成用户体验下降。
1.1开启 Mybatis 的延迟加载策略
Mybatis默认没有打开懒加载配置,我们需要在 Mybatis 的主配置文件中添加延迟加载的配置。
设置项 | 描述 | 允许 值 | 默认值 |
---|---|---|---|
lazyLoadingEnabled | 是否开启懒加载 | true /false | false |
aggressiveLazyLoading | 当设置为true的时候,懒加载的对象可能被任 何懒属性全部加载(不管是否被调用都会加载进 来)。否则,每个属性都按需加载(用到的时候 才会加载) | true /false | false(true <= 3.4.1) |
<!-- 开启延迟加载-->
<setting name="lazyLoadingEnabled" value="true"/>
<setting name="aggressiveLazyLoading" value="false"/>
1.2 使用 assocation 实现延迟加载
//接口
//查询所有账户
List<Account> findAll();
//映射层
<resultMap id="accountMap" type="account">
<id column="id" property="id"></id>
<result column="uid" property="uid"/>
<result column="money" property="money"/>
<association property="accountUser" javaType="AccountUser"
select="top.wutiaojian.demo.mapper.IAccountMapper.findByUserId"
column="uid">//查询的是
</association>
</resultMap>
<select id="findAll" resultMap="accountMap">
select * from account
</select>
//测试
@Test
public void findAll() {
//这时没有涉及到对User对象的操作,因此没有发出对User对象进行查询的SQL语句
List<Account> accounts = accountMapper.findAll();
/*for (Account account :
accounts) {
System.out.println(accounts);
}*/
}
//编译过后的SQL语句: Preparing: select * from account
//如果此时我们对accounts集合进行遍历,就会涉及到对User对象的操作,触发对User进行查询的SQL语句
//22:19:47,902 DEBUG findAll:143 -==> Preparing: select * from account
//22:19:47,954 DEBUG findAll:143 -==> Parameters:
//22:19:48,027 DEBUG findAll:143 -<== Total: 4
//22:19:48,028 DEBUG IAccountMapper:60 -Cache Hit Ratio //[top.wutiaojian.demo.mapper.IAccountMapper]: 0.0
//22:19:48,028 DEBUG findByUserId:143 -==> Preparing: select * from user where id = ?
//22:19:48,029 DEBUG findByUserId:143 -==> Parameters: 1(Integer)
//22:19:48,035 DEBUG findByUserId:143 -<== Total: 1
//Account(id=1, uid=1, money=1000.0, user=User(id=1, username=zhangsan, password=123456))
近期评论