ORM框架是有缓存的,例如mybtis,常说的缓存也就是一级缓存和二级缓存,其中一级缓存存在SqlSession的map中,二级缓存是在mapper上面
而相同sql在重复查询的时候,mybatis会优先拿取缓存中数据。一级缓存SqlSession在与数据库连接中开启,然后在方法执行结束或者方法出现异常时关闭
那么如果我们现在有需求每一次查询的时候都要拿取数据库最新的数据,该如何做呢?
特定sql的SqlSession一级缓存
1、每次执行sql之前清除缓存
public void testClearSqlSessionCache() throws Exception {
try (SqlSession sqlSession = SqlSessionFactory.class.newInstance().openSession()) {
TestMapper mapper = sqlSession.getMapper(TestMapper.class);
// 查询之前清空一级缓存
sqlSession.clearCache();
// 查询
Student student = mapper.selectStudent(Student.builder().name("xiaoming").build());
}
}
2、针对xml特定的sql,配置useCache=false
<select id="testSelect" parameterType="com.springboot.demo.entity.Student" useCache="false">
select * from student where age = #{age}
</select>
3、对于使用@Select注解的sql
@Select("select * from student where age = #{age}}")
@Options(useCache = false)
Student selectByAnnotation(@Param("age") Integer age);
4、对于使用mybatis-plus的QueryWrapper或LambdaQueryWrapper查询的
由于QueryWrapper不提供清除一级缓存的功能,但是本质上操作一级缓存还是SqlSession,所以可以使用方法一,手动清除sqlSession
public void testClearSqlSessionCache() throws Exception {
try (SqlSession sqlSession = SqlSessionFactory.class.newInstance().openSession()) {
StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
// 清空一级缓存
sqlSession.clearCache();
// 查询
LambdaQueryWrapper<Student> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.eq(Student::getAge, 10);
studentMapper.selectList(queryWrapper);
}
}