最近在做项目时遇到一个问题,springboot+mybatis项目,执行批量更新语句,坐了分批次执行批量更新,控制台打印更新成功,然后程序还没跑完,我就关闭程序了。可是当我回到数据库里面查看的时候,发现数据并没有改变,特此去研究了一下。

示例

Map<String, Object> map = new HashMap<>();
        Integer count = mapper.getCount();
        int size = 100;
        int m = count/size;
        map.put("size", size);
        for (int i = 0; i <= m; i++) {
            map.put("startIndex", i * size);
            List<NewsContentDO> contents = mapper.getAllNewsContentBy(map);
            for (NewsContentDO newsContentDO : contents) {
                String path = "/Users/admin/Desktop/pdf";
                newsContentDO.setPdfUrl(path);
            }
            mapper.updateBatch(contents);
        }
打开mybatis的日志,控制台会打印每次批量更新方法的日志,显示更新成功,改变行数等信息。但是这个时候停止程序,数据库是没有任何变化的。
这个原因是因为mybatis默认不是自动提交事务的, 所以其实没有修改数据库,刚刚新增完后立即返回的结果,是从mybatis为了提高性能设置的缓存里读取的,不是从数据库读取的。

解决方法

  1. 设定自动提交openSession( autoCommit=true)
public static SqlSession createSqlSession() {
    sqlSession = getSqlSessionFactory().openSession(true);
    return sqlSession;
}
  1. 在代码里面写上commit
sqlSession.commit();

miraclewu
4 声望1 粉丝