Java Spring @Transactional method not rolling back as expected

后端 未结 3 2002
伪装坚强ぢ
伪装坚强ぢ 2020-12-29 00:09

Below is a quick outline of what I\'m trying to do. I want to push a record to two different tables in the database from one method call. If anything fails, I want everythin

3条回答
  •  礼貌的吻别
    2020-12-29 00:39

    I found the solution!

    Apparently Spring can't intercept internal method calls to transactional methods. So I took out the method calling the transactional method, and put it into a separate class, and the rollback works just fine. Below is a rough example of the fix.

    public class Foo {
        public void insertRecords(List records){
            Service myService = new Service();
            for (Record record : records){
                myService.insertIntoAAndB(record);
            }
        }
    }
    
    public class Service {
        MyDAO dao;
    
        @Transactional (rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW)
        public void insertIntoAAndB(Record record){
            insertIntoA(record);
            insertIntoB(record);
        }
    
        @Transactional(propagation = Propagation.REQUIRED)
        public void insertIntoA(Record record){
            dao.insertIntoA(record);
        }
    
        @Transactional(propagation = Propagation.REQUIRED)
        public void insertIntoB(Record record){
            dao.insertIntoB(record);
        }
    
        public void setMyDAO(final MyDAO dao) {
            this.dao = dao;
        }
    }
    

提交回复
热议问题