I am reading the Transaction Management of Java EE 7 and I get confused by the concept of nested transaction and the functionality of EJBContext#setRollbackOnly()
.
Say I have two Session Beans, Bean1Impl
and Bean2Impl
and their signatures are:
@Stateless
@TransactionManagement(TransactionManagementType.CONTAINER)
public class Bean1Impl implements Bean1 {
@Resource
private EJBContext context;
@TransactionAttribute(REQUIRED)
public void method1() {
try {
//some operations such as persist(), merge() or remove().
}catch(Throwable th){
context.setRollbackOnly();
}
}
}
@Stateless
@TransactionManagement(TransactionManagementType.CONTAINER)
public class Bean2Impl implements Bean2 {
@Resource
private EJBContext context;
@TransactionAttribute(REQUIRED)
public void method2() {
try {
//some operations such as persist(), merge() or remove().
//an exception has been thrown
}catch(Throwable th){
context.setRollbackOnly();
}
}
}
As stated in Java EE 7 Tutorial:
51.3.1.1 Required Attribute
If the client is running within a transaction and invokes the enterprise bean's method, the method executes within the client's transaction. If the client is not associated with a transaction, the container starts a new transaction before running the method.
The Required attribute is the implicit transaction attribute for all enterprise bean methods running with container-managed transaction demarcation. You typically do not set the Required attribute unless you need to override another transaction attribute. Because transaction attributes are declarative, you can easily change them later.
In this case I don't need to specify @TransactionAttribute(REQUIRED)
annotation declaration in the methods Bean1Impl#method1()
and Bean2Impl#method2()
. Am I right?
So in the above code the transaction of Bean2Impl#method2()
would be running within the transaction of Bean1Impl#method1()
.
Can I consider it as a Nested Transaction?
If there is an Exception
has been thrown inside the method Bean2Impl#method2()
which eventually would lead to a call to the method EJBContext.setRollbackOnly()
from the catch
block and as expected it should roll back the operations performed within the try
block of this method. In this case what would happen to the transaction and as well as the Bean1Impl#method1()
. Would it be rolled back as well? What I mean is:
What would happen if there is a call of EJBContext.setRollbackOnly()
from Bean2Impl#method2()
and
Bean2Impl#method2()
is called from the methodBean1Impl#method1()
before any database operation like persist, merge or remove.Bean2Impl#method2()
is called from the methodBean1Impl#method1()
after any database operation like persist, merge or remove.
And lastly what would happen if the method Bean2Impl#method2()
get executed successfully but EJBContext.setRollbackOnly()
is called from Bean1Impl#method1()
after successful return of Bean2Impl#method2()
?