Annotation @Transactional. How to rollback?

后端 未结 4 1938
长情又很酷
长情又很酷 2020-11-28 02:53

I used this annotation successfully for a Dao class. And rollback works for tests.

But now I need to rollback real code, not just tests. There are special annotatio

相关标签:
4条回答
  • 2020-11-28 03:04

    For me rollbackFor was not enough, so I had to put this and it works as expected:

    @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackFor = Exception.class)
    

    I hope it helps :-)

    0 讨论(0)
  • 2020-11-28 03:12

    or programatically

    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
    
    0 讨论(0)
  • 2020-11-28 03:20

    Just throw any RuntimeException from a method marked as @Transactional.

    By default all RuntimeExceptions rollback transaction whereas checked exceptions don't. This is an EJB legacy. You can configure this by using rollbackFor() and noRollbackFor() annotation parameters:

    @Transactional(rollbackFor=Exception.class)
    

    This will rollback transaction after throwing any exception.

    0 讨论(0)
  • 2020-11-28 03:26

    You can throw an unchecked exception from the method which you wish to roll back. This will be detected by spring and your transaction will be marked as rollback only.

    I'm assuming you're using Spring here. And I assume the annotations you refer to in your tests are the spring test based annotations.

    The recommended way to indicate to the Spring Framework's transaction infrastructure that a transaction's work is to be rolled back is to throw an Exception from code that is currently executing in the context of a transaction.

    and note that:

    please note that the Spring Framework's transaction infrastructure code will, by default, only mark a transaction for rollback in the case of runtime, unchecked exceptions; that is, when the thrown exception is an instance or subclass of RuntimeException.

    0 讨论(0)
提交回复
热议问题