Rolling back a transaction in TransactionManagementType.CONTAINER EJB

Submitted by Jochus on Tue, 06/11/2012 - 22:33 | Posted in: Java

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

The content of this field is kept private and will not be shown publicly.

Full HTML

  • Lines and paragraphs break automatically.
  • You can caption images (data-caption="Text"), but also videos, blockquotes, and so on.
  • Web page addresses and email addresses turn into links automatically.
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>, <bash>, <cpp>, <css>, <html5>, <java>, <javascript>, <php>, <sql>, <xml>. The supported tag styles are: <foo>, [foo].
CAPTCHA
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.