最近在做專案時遇到一個問題,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為了提高性能設定的快取里讀取的,不是從資料庫讀取的,
解決方法
- 設定自動提交openSession( autoCommit=true)
public static SqlSession createSqlSession() {
sqlSession = getSqlSessionFactory().openSession(true);
return sqlSession;
}
- 在代碼里面寫上commit
sqlSession.commit();
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/185743.html
標籤:Java
上一篇:從無到有Springboot整合Spring-data-jpa實作簡單應用
下一篇:Git 程式員篇
