这份 Mybaits 缓存机制总结,阿里大佬看完直呼牛批,到底有多强?

Hello,今天给各位童鞋们分享 Mybaits 缓存,赶紧拿出小本子记下来吧!

1.一级缓存
本地缓存
与数据库同一次会话期间查询到的数据会放在本地缓存中
以后如果需要获取相同的数据,直接从缓存中拿
一级缓存是自动开启的。下面的 4 种方法是使得一级缓存失效的
1.sqlSession 不同
2.sqlSession 相同,查询条件不同
3.sqlSession 相同,查询期间执行了增删操作
4.手动清除了一级缓存
1.1 一级缓存初体验
@Test
public void test1()throws Exception{
SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
SqlSession openSession = sqlSessionFactory.openSession();
EmployMapper mapper = openSession.getMapper(EmployMapper.class);
Employee id = mapper.getId(2);
System.out.println(id);
Employee id1 = mapper.getId(2);
System.out.println(id1);
openSession.close();
}

由于有一级缓存的缘故,所以不用再调用 sqlSession
1.2 一级缓存失效
sqlSession 不同
@Test
public void test1()throws Exception{
SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
SqlSession openSession = sqlSessionFactory.openSession();
EmployMapper mapper = openSession.getMapper(EmployMapper.class);
Employee id = mapper.getId(2);
System.out.println(id);
SqlSession openSession1 = sqlSessionFactory.openSession();
EmployMapper mapper1 = openSession1.getMapper(EmployMapper.class);
Employee id1 = mapper1.getId(2);
System.out.println(id1);
openSession.close();
}

由于 SqlSession 的不同
使得没有缓存
2.sqlSession 相同,查询条件不同


3.sqlSession 相同,查询期间执行了增删操作


4.手动清除了一级缓存

执行了 openSession.clearCache()方法

2.二级缓存
全局缓存
是基于 namespace 级别的缓存,一个 namespace 对一个二级缓存
1.查询一条数据,放在一级缓存
2.如果会话关闭,一级到二级,新的会话信息,会参照二级缓存
3.不同的 namespace 会放在不同的 map 中,不同的二级缓存中
2.1 开启二级缓存
<settings>
<!--//开启二级缓存-->
<setting name="cacheEnabled" value="true"/>
</settings>
开启二级缓存

test.java
@Test
public void test2()throws Exception{
SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
SqlSession openSession = sqlSessionFactory.openSession();
SqlSession openSession1 = sqlSessionFactory.openSession();
EmployMapper mapper = openSession.getMapper(EmployMapper.class);
EmployMapper mapper1 = openSession1.getMapper(EmployMapper.class);
Employee id = mapper.getId(3);
System.out.println(id);
openSession.close();
Employee id1 = mapper1.getId(3);
System.out.println(id1);
openSession1.close();
}
注意要关闭再获取第二个,不然不会开启二级缓存,因为只有会话关闭的时候一级缓存才会转为二级缓存

2.2 二级缓存的属性

cacheEnabled=“true”
开启二级缓存
cacheEnabled=“false”
关闭二级缓存,但是一级缓存没有关闭

useCache=“false”
则二级缓存不可以使用,但是一级缓存还可以使用

flushCache="true"的话一级和二级缓存都会清除
默认为 false
3.缓存原理图

缓存查询顺序:
二级缓存
一级缓存
数据库
好啦,今天的文章就到这里,希望能帮助到屏幕前迷茫的你们!
评论