- 二级缓存是SqlSessionFactory级别,通过同一个SqlSessionFactory创建的SqlSession查询的结果会被缓存;此后若再次执行相同的查询语句,结果就会从缓存中获取。
二级缓存开启的条件:
- 1.在核心配置文件中,设置全局配置属性cacheEnabled="true",默认为true,不需要设置
- 2.在映射文件中设置标签
- 3.二级缓存必须在SqlSession关闭或提交之后有效
- 4.查询的数据所转换的实体类类型必须实现序列化的接口
使二级缓存失效的情况:
- 两次查询之间执行了任意的增删改,会使一级和二级缓存同时失效
CacheMapper接口
public interface CacheMapper {
Emp getEmpById(@Param("empId") Integer empId);
MyBatis的映射文件CacheMapper.xml
"1.0" encoding="UTF-8" ?>
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.atguigu.mybatis.mapper.CacheMapper">
<select id="getEmpById" resultType="Emp">
select * from t_emp where emp_id = #{empId}
测试
public class CacheMapperTest {
public void testCache() throws IOException {
InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
SqlSession sqlSession1 = sqlSessionFactory.openSession(true);
CacheMapper mapper1 = sqlSession1.getMapper(CacheMapper.class);
Emp emp1 = mapper1.getEmpById(1);
System.out.println(emp1);
SqlSession sqlSession2 = sqlSessionFactory.openSession(true);
CacheMapper mapper2 = sqlSession2.getMapper(CacheMapper.class);
Emp emp2 = mapper2.getEmpById(1);
System.out.println(emp2);
