5.4.5.2. Declarative Transaction Management
Any method of the Middleware managed bean may be annotated with @org.springframework.transaction.annotation.Transactional
, which will automatically create a transaction when the method is called. Such method does not require invoking Persistence.createTransaction()
, you can immediately get EntityManager
and work with it.
@Transactional
annotation supports a number of parameters, including:
-
propagation
- transaction creation mode. TheREQUIRED
value corresponds togetTransaction()
, theREQUIRES_NEW
value – tocreateTransaction()
. The default value isREQUIRED
.@Transactional(propagation = Propagation.REQUIRES_NEW) public void doSomething() { }
-
value
- data store name. If omitted, the main data store is assumed. For example:@Transactional("db1") public void doSomething() { }
Declarative transaction management allows you to reduce the amount of boilerplate code, but it has the following drawback: transactions are committed outside of the application code, which often complicates debugging because it conceals the moment when changes are sent to the database and the entities become Detached. Additionally, keep in mind that declarative markup will only work if the method is called by the container, i.e. calling a transaction method from another method of the same object will not start a transaction.
With this in mind, we recommend using declarative transaction management only for simple cases like a service method reading a certain object and returning it to the client.