0
votes

How do I get informed in a stateless session bean that the transaction need to be rolled back? For example, I have a stateless EJB which is updating a LuceneIndex with some business data. The method is called in a transaction with several EJB calls. When some of the later EJBs rolls back the transaction, than how can I be informed about this issue so that I am able to roll back my already written LuceneIndex entry?

2

2 Answers

1
votes

You can do this by injecting a reference to the current EJBContext and then querying it:

 @Stateless
 public class LuceneDriver {

     @Resource
     private EJBContext ejbContext;

     public void performLuceneStuff(...) {
         try {
             ...
             // update lucene data
             ...
             // update some business data
             ...
         } catch (BusinessException e) {
             if (ejbContext.getRollbackOnly()) {
                 // rollback lucene changes
             }
         }
     }

     ...

}
0
votes

If a session EJB is not transactional you won't be able to rollback in case of a failure. This is because of the missing state information of stateless session EJBs.

One solution to solve this issue is to use a @Stateful session bean that implements the javax.ejb.SessionSynchronization interface. This interface allows you to react on a rollback.

Another solution is to work with custom EventLog entries written by the main transaction via JPA. With those eventLog entries another stateless session EJBs can verify if new EventLog entries exist and if, they can react on it. If the trancaction was rolled back, also the uncommitted EventLog entries will be removed by the transaction manager. So this is a solution to couple non-transactional functionality to a JPA container based transaction. See the question: How to react on a EJB3 transaction commit or rolleback?