Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

On services and @Transactional

If I have a service class which calls three other service classes in a row, and each of those sub-services has to deal with a DAO object at some point, how can I make so that the wrapper service wraps them all into a single transaction? Will it be as simple as annotating the wrapper with @Transactional? What if the DAO is already marked as @Transactional?

like image 716
Preslav Rachev Avatar asked Oct 28 '25 13:10

Preslav Rachev


2 Answers

The default transaction propagation in Spring framework is REQUIRED, which means that the transaction is created if it does not already exist or the code joins existing one:

Support a current transaction, create a new one if none exists. Analogous to EJB transaction attribute of the same name.

This is the default setting of a transaction annotation.

This means that if you wrap calls to three transactional methods in a single transactional method, they will all run within a single transaction. Just like that.

See also:

  • What is the right way to use spring MVC with Hibernate in DAO, sevice layer architecture
like image 133
Tomasz Nurkiewicz Avatar answered Oct 30 '25 12:10

Tomasz Nurkiewicz


If you annotate the outer service as @Transactional and your DAOs are also @Transactional and called by the service they will by default join the outer transaction as you're hoping.

like image 35
Alex Barnes Avatar answered Oct 30 '25 13:10

Alex Barnes