4.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. The main parameter is the transaction creation mode – Propagation. The REQUIRED value corresponds to getTransaction(), the REQUIRES_NEW value – to createTransaction(). The default value is REQUIRED.

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.