Ad

Monday 17 August 2009

To Rollback the Transaction in EJB when an exception occurs

The most common usage of EJB is to handle transactions.When an EJB bean is invoked the transaction will be started by the EJB Container.Whenever there is a problem or exceptions occurs in between the transaction,we need to rollback the transaction completely.There are two approaches EJB provides us to handle this rollback.

(1)Annotating the user defined exception as Application Exception:
       we need to identify the business exceptions that can be thrown by the business logic in our application.Then we have to annotate this exception as javax.ejb.ApplicationException,so that the container will rollback the transaction whenever this business exception is thrown in between the EJB transaction.
The below example shows us how to annotate an user defined exception as Application Exception:

@ApplicationException(rollback=true)                                                                                                    
public class UploadException extends java.lang.Exception {
}

whenever UploadException is thrown in between the EJB transaction,the EJB container will automatically rollback the transaction.
Note:All the Run time exception and the Remote Exception will be rollback automatically by the container

(2) using setRollbackonly() method in the EJB bean:
       Another approach is to use the setRollbackOnly() method of the SessionContext Class.
 The below EJB bean example will show how to use this method.

@Stateless                                                                                                                                            
public class SessionBeanSample implements sampleinterface
{
@Resource
SessionContext ctx;//Get the sessioncontext
public void uploadFile()
{
try
{
//Business Logic
}
catch(Exception e)
{
ctx.setRollbackonly();//By calling the setRollbackOnly on the sessioncontext
} //makes the container to rollback the transcation when
} //any exception occurs in the method uploadFile().

No comments:

Post a Comment