一级缓存
获得结果时存入
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();
}
测试结果:



