阿超
>
mybatis判断批量操作是否全部执行成功
报纸是这个世界的镜子。——埃利斯
例如这样的代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
| import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.ExecutorType; import java.util.List; import org.apache.ibatis.executor.BatchResult;
public class BatchOperationExample { public boolean checkAllBatchResultsSuccessful(List<BatchResult> batchResults) { for (BatchResult result : batchResults) { int[] updateCounts = result.getUpdateCounts(); for (int count : updateCounts) { if (count <= 0) { return false; } } } return true; }
public static void main(String[] args) { SqlSession sqlSession = null; try { sqlSession = MyBatisUtil.getSqlSession(ExecutorType.BATCH);
sqlSession.commit(); List<BatchResult> batchResults = sqlSession.flushStatements();
BatchOperationExample example = new BatchOperationExample(); boolean allSuccess = example.checkAllBatchResultsSuccessful(batchResults); System.out.println("All batch operations successful: " + allSuccess); } catch (Exception e) { sqlSession.rollback(); e.printStackTrace(); } finally { if (sqlSession != null) { sqlSession.close(); } } } }
|
不过也可以用Stream
流的写法
1
| batchResults.stream().flatMapToInt(r-> IntStream.of(r.getUpdateCounts())).allMatch(i->i>0);
|
核心就一点,就是注意每一个getUpdateCounts
都大于0
即可