0
votes

I have the following example:

public class MyEJBService implements javax.ejb.SessionBean {
      public void modifyAllItems() {
           doSomething...
           for(...)
           {
                modifyItem(item);
           }
      }


     public void modifyItem(Item item) {
          doSomething...
     }
}

Method 1 = modifyAllItems Method 2 = modifyItem

Method1 calls method2 several times. I want to disable the transaction at method1 but enable the transaction at method2. Each call of method2 should be at a different transaction (if an error occurs while modifying an item, some items could have been modified while others remains unchanged). I've defined an EJB transaction type for method1() - NEVER and another for method2() - REQUIRES NEW. The problem is that it seems that when I'm calling method2(), the EJB is not creating any transaction because when an error occurs inside method2() it is not rolling back (if something is changed at the database inside method2 but it throws an exception before method2 completition the database is not returning to the previous state - rollback). Is this behavior expected? I'm a little bit confused. Thank you very much.

2

2 Answers

2
votes

Yes it's the expected behavior as transaction are implemented using a proxy and so applied only when the call to the EJB method is done from a third party object. If you want method2() transaction to be applied when called from method1() you have to move it to a second EJB object.

1
votes

Another idea is Bean Managed Transaction,belowing are the steps

  1. ejb-jar.xml

    <transaction-type>Bean</transaction-type>

  2. the code

    public class MyEJBService implements javax.ejb.SessionBean {
    SessionContext context;

    public void modifyAllItems() 
    {
        doSomething();
         for(...)
         {
             UserTransaction  trans=context.getUserTransaction();;
             try
             {
              trans.begin();
              modifyItem(item);
              trans.commit();
             }catch(Exception  e)
             {
                 trans.rollback();//if need propagation then:trans.setRollbackOnly();
             }
         }
    }
    
    public void modifyItem(Item item) {
        doSomething();
    }
    
    @Override
    public void setSessionContext(SessionContext context) throws EJBException,
            RemoteException {
        this.context = context;
    }