Spring hibernate , how to call some method after transaction commit or transaction rollback

前端 未结 3 1818
心在旅途
心在旅途 2020-12-05 19:59

I need to call some method after transaction succes or rollback. I am using as

    

        
3条回答
  •  萌比男神i
    2020-12-05 20:22

    Using Spring 4+: The easiest/cleanest way without using global aspects and configurations is based on my answer here: https://stackoverflow.com/a/43322052/986160

    If you need a callback on a @Transactional method after it successfully commits just add that in the beginning of the method:

    @Service
    public class OneService {
    
        @Autowired
        OneDao dao;
    
        @Transactional
        public void a transactionalMethod() {
            TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter(){
                public void afterCommit(){
                    //do stuff right after commit
                    System.out.println("commit!!!");
    
                }
            });
            //do db stuff
            dao.save();
        }
    }
    

提交回复
热议问题