I would like to ask question regarding EJB. I am using eclipselink of JPA.
There is two stateless objects in a stateless object in my code.
Is that possible this two stateless object use two different transactions?
Absolutely. You may find it useful to read about the transaction attributes.
If the called method in your first class (say StatelessFirst
) has a transaction type REQUIRED
(the default) or REQUIRES_NEW
, when it is called it will initiate a new transaction. If this then calls a method in your second class (say StatelessSecond
) with transaction type REQUIRES_NEW
, the first transaction is suspended and a second transaction is initiated while the second method executes. When the method in StatelessSecond
completes, the second transaction commits, the first transaction is reinstated, and control is passed back to StatelessFirst
.
To make the first transaction commit before StatelessSecond
is called, you can use bean-managed transactions. This gives you full control over the transaction management, so in StatelessFirst
you can begin a transaction, then commit then call StatelessSecond
. If you go with this approach, note that you can't perform nested transactions in BMT.
One other option which allows you to stay within CMT would be to pull the transactional behaviour out of StatelessFirst
into a third EJB, with REQUIRES_NEW
. Then the pattern is:
StatelessFirst
, which initiates transaction AStatelessFirst
calls NewBean
, which initiates transaction B, and performs some workNewBean
commits transaction B and returnsStatelessFirst
calls StatelessSecond
, which initiates transaction C, and performs its workStatelessSecond
commits transaction C and returnsStatelessFirst
completes, and commits transaction A (which doesn't have any changes anyway)