Search code examples
springtransactionsspring-dataspring-transactions

@TransactionalEventListener with @Transactional and propagations REQUIRES_NEW, NOT_SUPPORTED


I don't understand why this is needed now. I can't start my application because I have a service with @Transactional annotation and some methods with @TransactionalEventListener, and everything was fine - everything worked as needed.

Needed: I create entity A in AService, then publish an event that entity A created. Then services that listen to events about the creation of entity A create their entities that depend on entity A - like 5-10 services. All these creations need to be done in one transaction.

Now I have to create a new transaction (REQUIRES_NEW), and if something goes wrong, I can't roll back A entity. Why is this?

I have seen these questions about this, but I don't understand...

https://github.com/spring-projects/spring-framework/issues/30679
https://github.com/spring-projects/spring-framework/pull/33470


Solution

  • Assuming you are using "BEFORE_COMMIT" transaction phase since you want them to run all in one transaction. When you have a @TransactionalEventListener with phase "BEFORE_COMMIT" implies that there is already an active transaction. You don't need to put another @Transactional annotation. It causes some problems when used with default "AFTER_COMMIT" which is described in detail here, like you mentioned.

    Now I have to create a new transaction (REQUIRES_NEW), and if something goes wrong, I can't roll back A entity. Why is this?

    No, you don't have to set propagation to "REQUIRES_NEW". You can remove unnecessary @Transactional annotation.

    You can also validate if the code is being executed in transaction with the help from: TransactionSynchronizationManager.isActualTransactionActive()