views:

34

answers:

2

Imagine the following two ejb3.0 stateless session beans, each implements a local interface and they are deployed to the same container:

public class EjbA {
    @EJB 
    private ejbB;

    public void methodA() {
        for (int i=0; i<100; i++) {
            ejbB.methodB();
        }
    }    
}

public class EjbB {
    public void methodB() {
        ...
    }
}

When methodA is invoked, does each call to methodB cause a new transaction to begin and commit? Or, since these a both local beans, is there one transaction that begins when methodA is called and is re-used by methodB?

Cheers!

+2  A: 

It depends on your transaction attribute - which you can set with the @TransactionAttribute annotation to one of:

  • REQUIRED
  • REQUIRES_NEW
  • SUPPORTS
  • MANDATORY
  • NOT_SUPPORTED
  • NEVER

REQUIRED is the default, and will start a new transaction if there is no transaction in place, otherwise the container uses the existing transaction.

REQUIRES_NEW tells the container to always start a new transaction.

The other options are less commonly used in my experience - but they are all defined in the EJB specification.

For example:

@Stateless
public class EjbA {
    @EJB 
    private ejbB;

    @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
    public void methodA() {
        for (int i=0; i<100; i++) {
            ejbB.methodB();
        }
    }    
}

... would make methodA() always run in a new transaction.

richj
A: 

it depends how you define transaction strategy for each method.

if its Required in method B and A : it will use same transaction for both

if its Required for A and Requires New for B : it will create new transaction for method B

mohammad shamsi