目录
2.在mybatis的sqlmap中配置(mapper.xml中配置)
4.在接口的定义上面直接使用@CacheNamespace 并将blocking设置为true,二级缓存就可以使用了
查询缓存
MyBaits提供了一级缓存和二级缓存功能,目的是为了减少数据库查询操作,提高系统的应用性能。
一级缓存是sqlSession的缓存。操作数据库时会创建sqlSession对象,该对象内部有一个数据结构(HashMap)用户存储缓存数据。不同的sqlSession对象都有各自的HashMap,之间不会相互影响。
二级缓存是Mapper级别的缓存,多个sqlSession操作同一个Mapper中的查询,多个SqlSession可以共用同一个缓存,二级缓存是跨SqlSession的。
如果缓存中已经有了查询语句所对应的数据,那么就不用再访问数据库了,直接从缓存中取数据就可以了,这样便提高了应用系统的性能。
一级缓存
一级缓存的过程:
第一次发起查询的时候,先去缓存中找是否有id为2的信息,如果没有则去数据库中查询,将查询到的信息先要保存到一级缓存中。然后将信息传出去。
第一次发起查询的时候,先去缓存中找是否有id为2的信息,缓存中有第一次查询到的信息,直接将缓存中的信息传出去,此次不会进行访问数据库。
如果sqlSession进行增删改(无论是否提交),就会清空缓存,这样做是为了保证缓存中的数据和数据库中变化后的数据要保持一致,防止有脏读的情况。
一级缓存的测试
package com.ape.test;
import org.apache.ibatis.session.SqlSession;
import com.ape.bean.Student;
import com.ape.dao.DaoUtil;
import com.ape.mapper.StudentMapper;
public class demo2 {
public static void main(String[] args) {
SqlSession sqlSession = DaoUtil.getSqlSession();
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
Student s = mapper.findStudentBySid(1);
System.out.println(s);
System.out.println("--------------------------");
Student s2 = mapper.findStudentBySid(1);
System.out.println(s2);
System.out.println(s==s2);
DaoUtil.closeResource(sqlSession);
// 不同的sqlSession进行操作
// SqlSession sqlSession = DaoUtil.getSqlSession();
// StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
// Student s = mapper.findStudentBySid(1);
// System.out.println(s);
// System.out.println("--------------------------");
// SqlSession sqlSession2 = DaoUtil.getSqlSession();
// StudentMapper mapper2 = sqlSession2.getMapper(StudentMapper.class);
// Student s2 = mapper2.findStudentBySid(1);
// System.out.println(s2);
// System.out.println(s==s2);
// DaoUtil.closeResource(sqlSession);
//增删改清空缓存
// SqlSession sqlSession = DaoUtil.getSqlSession();
// StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
// Student s = mapper.findStudentBySid(1);
// System.out.println(s);
// S