欢迎您访问365答案网,请分享给你的朋友!
生活常识 学习资料

Mybatis——二级缓存

时间:2023-06-11
两个区域

一级缓存
获得结果时存入
SqlSession级别的。
默认开启。

二级缓存
会话关闭时存入
应用级别的。
需要手动开启配置。

测试一级

同一个Session:

@Testpublic void f1() throws IOException {InputStream is = Resources.getResourceAsStream("mybatis.xml");SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);SqlSession s1 = factory.openSession();StudentMapper m1 = s1.getMapper(StudentMapper.class);System.out.println(m1.findById(1));System.out.println(m1.findById(1));s1.close();}

测试结果:

不同的Session:

@Testpublic void f1() throws IOException {InputStream is = Resources.getResourceAsStream("mybatis.xml");SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);SqlSession s1 = factory.openSession();StudentMapper m1 = s1.getMapper(StudentMapper.class);System.out.println(m1.findById(1));s1.close();SqlSession s2 = factory.openSession();StudentMapper m2 = s2.getMapper(StudentMapper.class);System.out.println(m2.findById(1));s2.close();}

测试结果:

开启二级 全局配置Mapper配置实体类实现Serializable

全局配置

Mapper配置

几个属性:
eviction:回收策略
LRU(默认)
FIFO
SOFT
WEAK

flushInterval:自动清空间隔秒,默认不清空

readOnly:是否会变动

size:缓存数量

实体类实现

@Data@ToString@NoArgsConstructor@AllArgsConstructorpublic class Student implements Serializable {private Integer id;private String name;private Integer age;}

测试代码:

@Testpublic void f1() throws IOException {InputStream is = Resources.getResourceAsStream("mybatis.xml");SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);SqlSession s1 = factory.openSession();StudentMapper m1 = s1.getMapper(StudentMapper.class);System.out.println(m1.findById(1));s1.close();SqlSession s2 = factory.openSession();StudentMapper m2 = s2.getMapper(StudentMapper.class);System.out.println(m2.findById(1));s2.close();}

测试结果:

Copyright © 2016-2020 www.365daan.com All Rights Reserved. 365答案网 版权所有 备案号:

部分内容来自互联网,版权归原作者所有,如有冒犯请联系我们,我们将在三个工作时内妥善处理。