1.为什么要有缓存?
如果数据库在1秒钟之内有一万个请求过来,数据库承受不住,压力太大,这时就需要一个缓存存储已查询的数据。在第二次查询时就可以从缓存中拿数据,从而提高效率。
2.sqlSession生命周期
sqlSession创建(出生):SqlSessionFactory .openSession()
sqlSession关闭(死亡):sqlSession.close()
3.一级缓存
作用域:从sqlSession.openSession()开始到sqlSession.close()结束。当sqlsession执行更新操作或者close后,该Session中的所有Cache就将清空。这样做的目的为了防止出现脏读现象(读取数据与数据库不一致)。
Mybatis默认支持一级缓存,不需要在配置文件去配置。需要注意的是,必须是同一个session,才能从缓存中拿取数据。
以下代码均建立在mybatis环境下:
实验一:验证Mybatis是否支持一级缓存(是)
public static void testSelectStudent(Integer id){
SqlSession sqlSession= MybatisUtils.getSqlSession();
StudentMapper stuMapper=sqlSession.getMapper(com.wbw.mapper.StudentMapper.class);
Student student1 = stuMapper.selectStudent(id);//调用查询方法
System.out.println(student1);
Student student2 = stuMapper.selectStudent(id);//调用查询方法
System.out.println(student2);
Student student3 = stuMapper.selectStudent(id);//调用查询方法
System.out.println(student3);
sqlSession.close();
}
实验结果:
实验二:关闭缓存后mybatis是否还有缓存(没有)
public static void testSelectStudent(Integer id){
SqlSession sqlSession= MybatisUtils.getSqlSession();
StudentMapper stuMapper=sqlSession.getMapper(com.wbw.mapper.StudentMapper.class);
Student student1 = stuMapper.selectStudent(id);//调用查询方法
System.out.println(student1);
Student student2 = stuMapper.selectStudent(id);//调用查询方法
System.out.println(student2);
sqlSession.clearCache();//清空缓存
Student student3 = stuMapper.selectStudent(id);//调用查询方法
System.out.println(student3);
sqlSession.close();
}
实验结果:
实验三:执行sqlSession.close()操作后是否还有缓存(没有)
public static void testSelectStudent(Integer id){
SqlSession sqlSession= MybatisUtils.getSqlSession();
StudentMapper stuMapper=sqlSession.getMapper(com.wbw.mapper.StudentMapper.class);
Student student1 = stuMapper.selectStudent(id);//调用查询方法
System.out.println(student1);
Student student2 = stuMapper.selectStudent(id);//调用查询方法
System.out.println(student2);
sqlSession.close();//关闭sqlSession
Student student3 = stuMapper.selectStudent(id);//调用查询方法
System.out.println(student3);
}
实验结果:
程序报错,Exceutor was closed 因为执行了sqlSession.close(),就意味着这个sqlSession已经结束了,相当于死亡,自然缓存也不复存在。
解决办法:再重新创建一个SqlSession即可。
实验四:执行更新(添加、修改、删除)操作后,是否会清空缓存?(会)
查询方法:
public static void testSelectStudent(Integer id){
SqlSession sqlSession= MybatisUtils.getSqlSession();
StudentMapper stuMapper=sqlSession.getMapper(com.wbw.mapper.StudentMapper.class);
Student student1 = stuMapper.selectStudent(id);//调用查询方法
System.out.println(student1);
Student student2 = stuMapper.selectStudent(id);//调用查询方法
System.out.println(student2);
}
修改方法:
public static boolean testUpdateStudent(Student student){
SqlSession sqlSession= MybatisUtils.getSqlSession();
StudentMapper stuMapper=sqlSession.getMapper(com.wbw.mapper.StudentMapper.class);
boolean temp = stuMapper.updateStudent(student);
sqlSession.commit();
return temp;
}
测试:
testSelectStudent(8);//执行查询方法
Student student = new Student();
student.setStu_id(8);
student.setStu_age(11);
student.setStu_name("yangyanz");
testUpdateStudent(student);//执行修改方法
testSelectStudent(8);//执行查询方法
实验结果: