栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Mybatis——二级缓存

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Mybatis——二级缓存

两个区域

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

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

测试一级

同一个Session:

@Test
public 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:

@Test
public 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
@AllArgsConstructor
public class Student implements Serializable {
	private Integer id;
	private String name;
	private Integer age;
}

测试代码:

@Test
public 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();
}

测试结果:

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/736735.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号