
Rolling back a transaction in a TransactionManagementType.BEAN
First of all, there's a difference with a TransactionManagementType.BEAN EJB. When an EJB is marked with the @TransactionManagement(TransactionManagementType.BEAN) annotation, transaction management is performed by calling the methods in the UserTransaction class.
Example:
@Stateless @TransactionManagement(TransactionManagementType.BEAN) public class FooBarBean implements FooBar { @Resource private UserTransaction tx; public void someMethod() throws Exception { try { tx.begin(); // do something tx.commit(); } catch(Exception ex) { tx.rollback(); throws ex; } } ...
For every method in which you need a transaction, you have to control the UserTransaction by yourself.
Rolling back a transaction in a TransactionManagementType.CONTAINER
Example:
@Stateless public class FooBarBean implements FooBar { @Resource private EJBContext context; public void someMethod() throws Exception { try { // do something } catch(Exception ex) { context.setRollbackOnly(); throws ex; } } }
The transaction will be automatically started at the start of the method and it will be committed at the end of the method.
The moment when context.setRollbackOnly() is invoked, the transaction will just be marked as rollback only and nothing will be persisted when the method ends and returns.
Add new comment