一级缓存
默认开启
也叫本地缓存(SqlSession级别的)
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = mapper.queryUser(1);
System.out.println(user);
System.out.println("=================================");
User user2 = mapper.queryUser(1);
System.out.println(user2);
System.out.println(user==user2);
sqlSession.close();
两个查询语句查相同结果
Created connection 402115881.
==> Preparing: select * from user where id=?
==> Parameters: 1(Integer)
<== Columns: id, name, pwd
<== Row: 1, 张三, 1234567
<== Total: 1
User(id=1, name=张三, pwd=1234567)
=================================
User(id=1, name=张三, pwd=1234567)
true
Closing JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@17f7cd29]
Returned connection 402115881 to pool.
明显只执行了一次sql,这就是一级缓存
注意:
- 查询不同内容不会从缓存读取;
- 执行增删改会刷新缓存
- 一级缓存只在依次SqlSession中有效,即从拿到连接到关闭连接这个区间
二级缓存
手动开启:
步骤:
1.开启全局缓存
<settings>
<setting name="cacheEnabled" value="true"/>
</settings>
2.只要在Mapper.xml中添加一个标签就开启了
<mapper namespace="com.liu.dao.UserMapper">
<cache/>
二级缓存也叫全局缓存,基于namespace级别,一个名称空间,对应一个二级缓存;
- 一个会话sqlsession查询一条数据,这个数据就会被放在当前会话的一级缓存中;
- 如果当前会话sqlsession关闭了,一级缓存就无了。但是缓存会存放到二级缓存中
- 当新的对话出现,就可以到二级缓存中查找内容。 不同的mapper查询出的数据放在对应的自己的缓存中;
测试:
public void queryUser(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
SqlSession sqlSession2 = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
UserMapper mapper2 = sqlSession2.getMapper(UserMapper.class);
User user = mapper.queryUser(1);
sqlSession.close();
System.out.println(user);
System.out.println("=================================");
User user2 = mapper2.queryUser(1);
System.out.println(user2);
System.out.println(user==user2);
sqlSession2.close();
}
日志:
Opening JDBC Connection
Created connection 1886491834.
==> Preparing: select * from user where id=?
==> Parameters: 1(Integer)
<== Columns: id, name, pwd
<== Row: 1, 张三, 1234567
<== Total: 1
Closing JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@707194ba]
Returned connection 1886491834 to pool.
User(id=1, name=张三, pwd=1234567)
=================================
Cache Hit Ratio [com.liu.dao.UserMapper]: 0.5
User(id=1, name=张三, pwd=1234567)
true
只有当这个sqlSession关闭后, 内容才会到二级缓存
问题:在mapper.xml中仅使用会报序列化错误,使用
<cache
eviction="FIFO"
flushInterval="60000"
size="512"
readOnly="true"/>
不会报错,在于eviction
自定义缓存ehchache