/*
*缓存
* 一级缓存(本地缓存),sqlSession级别的缓存,一级缓存是一直开启的.
* 与数据库同一次会话期间查询到的数据会放在本地缓存中。
* 以后如果需要获取相同的数据,直接从缓存中取,没必要再去查询数据库
*
* 一级缓存的几种失效情况(没有使用到当前一级缓存的情况,效果就是,还需要再向数据库发出查询)
* 1. sqlSession不同,一个sqlSession是一个一级缓存.不同的sqlSession是不同的一级缓存
* 2. sqlSession相同,查询条件不同(当前一级缓存中还没有这个数据)
* 3. sqlSession相同,但两次查询之间执行了增删改操作(这次增删改可能对原来数据有影响)
* 4. sqlSession相同,手动清除了一级缓存(缓存清空)
* 二级缓存:(全局缓存)
*/
失效情况一:不同的sqlSession
@Test
public void testFirstLevelCache() throws IOException{
String resource = "mybatis-config.xml";
InputStream ins = Resources.getResourceAsStream(resource);
SqlSessionFactory sf = new SqlSessionFactoryBuilder().build(ins);
SqlSession openSession = sf.openSession();
try{
EmployeePlusMapper em = openSession.getMapper(EmployeePlusMapper.class);
Employee e1 = em.getEmpByDepnos(7369);
// 1. sqlSession不同,一个sqlSession是一个一级缓存.不同的sqlSession是不同的一级缓存
// 新建的sqlSession
SqlSession openSession2 = sf.openSession();
EmployeePlusMapper em2 = openSession2.getMapper(EmployeePlusMapper.class);
Employee e2 = em2.getEmpByDepnos(7369);
System.out.println(e1 == e2);
}finally{
openSession.close();
}
}
失效情况二:sqlSession相同,查询条件不同
@Test
public void testFirstLevelCache() throws IOException{
String resource = "mybatis-config.xml";
InputStream ins = Resources.getResourceAsStream(resource);
SqlSessionFactory sf = new SqlSessionFactoryBuilder().build(ins);
SqlSession openSession = sf.openSession();
try{
EmployeePlusMapper em = openSession.getMapper(EmployeePlusMapper.class);
Employee e1 = em.getEmpByDepnos(7369);
// sqlSession相同, 查询条件不一样
Employee e2 = em.getEmpByDepnos(7499);
System.out.println(e1 == e2);
}finally{
openSession.close();
}
}
失效情况三:sqlSession相同,但两次查询之间执行了增删改操作
@Test
public void testFirstLevelCache() throws IOException, ParseException{
String resource = "mybatis-config.xml";
InputStream ins = Resources.getResourceAsStream(resource);
SqlSessionFactory sf = new SqlSessionFactoryBuilder().build(ins);
SqlSession openSession = sf.openSession();
try{
EmployeePlusMapper em = openSession.getMapper(EmployeePlusMapper.class);
Employee e1 = em.getEmpByDepnos(7369);
// 执行增加操作
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date dd = formatter.parse("2019-04-03");
Employee employee = new Employee("1","tom","grammer",7902,dd,800.0);
em.addEmp(employee);
// sqlSession相同, 查询条件也一样
Employee e2 = em.getEmpByDepnos(7369);
System.out.println(e1 == e2);
}finally{
openSession.close();
}
}
失效情况四:sqlSession相同,手动清除了一级缓存
@Test
public void testFirstLevelCache() throws IOException, ParseException{
String resource = "mybatis-config.xml";
InputStream ins = Resources.getResourceAsStream(resource);
SqlSessionFactory sf = new SqlSessionFactoryBuilder().build(ins);
SqlSession openSession = sf.openSession();
try{
EmployeePlusMapper em = openSession.getMapper(EmployeePlusMapper.class);
Employee e1 = em.getEmpByDepnos(7369);
// 手动清除一级缓存
openSession.clearCache();
// sqlSession相同, 查询条件也一样
Employee e2 = em.getEmpByDepnos(7369);
System.out.println(e1 == e2);
}finally{
openSession.close();
}
}