Mybatis一级缓存和mybatisplus 踩坑记

事故描述

用mybatisPlus查询角色组,为0,

语句为:

//全量查询角色组信息
            List<RoleGroup> roleGroupList = roleGroupMapper.selectList(Wrappers.<RoleGroup>lambdaQuery().in(RoleGroup::getSource, source));

于是进行插入

然后在查出最新插入的数据,语句还是同上

在插入到另一张表中。

发现第二次查询没有执行

问题分析

会不会是因为插入行为在另一事务内?

查阅代码发现事务传播行为为默认属性:required ,也就是不会创建新事务,而是加入调用者的事务。

在考虑数据库的隔离级别

默认为读已提交,也没问题

在考虑mybatis的一级缓存

    一级缓存默认开启 一级缓存是session级别的 sqlsession执行dml (insert/update/delete)、close、clearCache等方法,会释放localcache中的对象(引用),一级缓存不可用

综上,删除再插入,然后重新获取时不会使用一级缓存。因此不应该是一级缓存

最后网上有篇文章这么回答

答案:

最后在重新走一遍,发现控制台的确不打印语句,用的永远是第一次的查询结果

  1. 难道是因为一个事务开启了多个sqlSession?

debug事务内部所有sql操作,查看sqlSession的内存地址

理论上在一个事务内,一个mapper对应开启一个sqlSession。

打印:update和selectList的sqlSession的内存地址

意外发现mybaits-plus在updateBatch的时候和update用的不是同一个sqlSession,这实在太坑了。

/**
com.baomidou.mybatisplus.extension.service.impl.ServiceImpl
*/
public class ServiceImpl<M extends BaseMapper<T>, T> implements IService<T> {
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean updateBatchById(Collection<T> entityList, int batchSize) {
        Assert.notEmpty(entityList, "error: entityList must not be empty");
        String sqlStatement = sqlStatement(SqlMethod.UPDATE_BY_ID);
        try (SqlSession batchSqlSession = sqlSessionBatch()) {
            int i = 0;
            for (T anEntityList : entityList) {
                MapperMethod.ParamMap<T> param = new MapperMethod.ParamMap<>();
                param.put(Constants.ENTITY, anEntityList);
                batchSqlSession.update(sqlStatement, param);
                if (i >= 1 && i % batchSize == 0) {
                    batchSqlSession.flushStatements();
                }
                i++;
            }
            batchSqlSession.flushStatements();
        }
        return true;
    }

    @Override
    public boolean updateById(T entity) {
        return retBool(baseMapper.updateById(entity));
    }
// 其他 
}

如上代码片断,mybatis-plus在updateBatch时的处理逻辑 使用Serivice内部打开的sqlSession ,而普通的updateById则走的mapper更新,mapper更新用的则是另一套session. 这也就是说

如前文所说,sqlSessionA未监听到update/delete句柄,因此未执行移除缓存的操作,这使得第二次selectList的时候未执行sql语句,直接从缓存中取。

总结

  1. mytabis一级缓存在表被删除更新操作时缓存对象引用会被移除
  2. 一级缓存是会话级别的
  3. mybatis-plus selectList和updateBatchBy方法使用了两个不同的sqlSession.

因第3条的缘故,使得一级缓存没有在理想状态下被移除从而引发事故。

经验分享 程序员 微信小程序 职场和发展