Mybatis-清除一级缓存SqlSession,每次查询都从数据库查询最新数据

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);
    }
}
  • 8
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

只吹45°风

一切随心,感激您的每一份支持。

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值