Are Java EE 6 CDI events transactional?
If I fire an event in a transaction, and subsequently roll back the transaction, are the effects of the Event listener rolled back as well?
Is this behaviour dependent on the event listener itself supporting transactions?
What about if I try and roll-back the exception from within then event listener, does it roll-back the transaction that fired the event?
Events allow beans to communicate without any compile-time dependency. One bean can define an event, another bean can fire the event, and yet another bean can handle the event. The beans can be in separate packages and even in separate tiers of the application.
CDI (Contexts and Dependency Injection) is a standard dependency injection framework included in Java EE 6 and higher. It allows us to manage the lifecycle of stateful components via domain-specific lifecycle contexts and inject components (services) into client objects in a type-safe way.
UserTransaction interface. These are the same interfaces that a session bean with bean-managed transactions can use. Transactions demarcated with the UserTransaction interface are discussed in JTA Transactions.
Customer data integration (CDI) is the process of defining, consolidating and managing customer information across an organization's business units and systems to achieve a "single version of the truth" for customer data.
From the events chapter of the CDI 1.0 specification, one can define an event to be "transactional" by specifying the TransactionPhase one is observing, where TransactionPhase is one of:
Such a declaration looks like:
void onDocumentUpdate(@Observes(during=AFTER_SUCCESS) @Updated Document doc) { ... }
If the observer is not declared to be "transactional", then the container calls the observer immediately, otherwise it registers the observer method for later invocation during the transaction completion phase, using a JTA Synchronization.
However:
Any observer method called before completion of a transaction may call setRollbackOnly() to force a transaction rollback. An observer method may not directly initiate, commit or rollback JTA transactions.
If the observer method throws an exception (and is itself not "transactional") the exception aborts processing of the event.
So, to achieve the behaviour I'm looking for, I believe I would register my observer as "transactional", and specify the BEFORE_COMPLETION TransactionPhase. I would then call setRollbackOnly() if I wanted to rollback the transaction that initiated the event.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With