07 - mybatis -缓存、延迟加载

缓存

1xml配置开启二级缓存

注意:开启缓存需要在核心配置文件中配置

<settings>
<setting name="cacheEnabled" value="true"/>
</settings>

如果使用的是xml配置sql的方式,那么必须在mapperxml中配置标签

2 注解方式开启二级缓存

1 核心配置文件开启配置

2 接口类上加入注解

@CacheNamespace(blocking = true)
public interface UserDao {

注意:二级缓存的时候必须在最后关闭session,也就是清理一级缓存

二次缓存查询案例

二次缓存是失去factory级别的

@Test
public void cache2() throws IOException {
   InputStream stream = Resources.getResourceAsStream("mybatis.xml");
   SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(stream);
   SqlSession sqlSession = factory.openSession();
   StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
   Student student = mapper.one();
   System.out.println(student);

   sqlSession.close();

   SqlSession sqlSession2= factory.openSession();
   StudentMapper mapper2 = sqlSession2.getMapper(StudentMapper.class);
   Student student2 = mapper2.one();
   System.out.println(student2);
}

11延迟加载

  1. 延迟加载必须导入两个包

cglib cglib 3.1 org.ow2.asm asm 4.2 ``` ```

  1. 在一对多的地方开启延迟加载,开启的地方可以选择全局开启,还是针对某个方法

==全局开机==

>```xml
><!-- 开启懒加载配置 -->
><settings>
>    <!-- 全局性设置懒加载。如果设为‘false',则所有相关联的都会被初始化加载。 -->
>    <setting name="lazyLoadingEnabled" value="true"/>
>    <!-- 当设置为‘true'的时候,懒加载的对象可能被任何懒属性全部加载。否则,每个属性都按需加载。 -->
>    <setting name="aggressiveLazyLoading" value="false"/>
></settings>
>```

==局部开启==

```xml
--在对应的一对多查询的地方collection开启
<collection property="teachers" ofType="teacher" column="id" select="cn.laixueit.mapper.TeacherMapper.teachers" fetchType="lazy">
</collection>

注解开启,在需要进行懒加载的地方添加属性fetchType=fetchType=lazy

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值