Alice52 / database

ddf13ad8d4be76a80a336418b5cf5727bf6e3059
gitee.com
MIT License
0 stars 0 forks source link

[mybatis] plus nest exception #48

Closed Alice52 closed 1 year ago

Alice52 commented 1 year ago
  1. saveBatch: mybatis-plus 为了可以保证事务所以添加了 @Transactional 注解
  2. 如果外层使用 @Transactional + try..catch 就可能引起嵌套事务报错
    Transaction rolled back because it has been marked as rollback-only
  3. sample code
     @Transactional(rollbackFor = Exception.class)
        public Boolean xxx(xxx dto) {
            list1 = .....;
            try {
                saveBatch(list1); // 报错会 marked as rollback-only
            } catch (Exception e) {
                if (e instanceof DuplicateKeyException) {
                      // 此时这个事务是不能提交的
                       The database saves the filtered list1 in batches;
                }
            }
    }
  4. Workaround
    • saveBatch 上的 @Transactional 注解删
    • Set the '@Transactional' annotation for mybatis-plus to set the transaction propagation mechanism to: REQUIRES_NEW or NESTED
    • 自己写批量 xml SQL