4

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?

Preslav Rachev
  • 3,983
  • 6
  • 39
  • 63
  • Just an aside - I don't think it's a good idea for your DAOs to be transactional. It's at the level of the service that you need operations to be atomic. Suppose your service updates a Person and its Address, and there's a failure updating the Address. You want to roll back the whole thing, right? So the `@Transactional` annotation ought to be only at the entry point into the services layer. (Though as responders have said, you can nest `@Transactional` methods and have them reuse the outer transaction.) – Andrew Spencer Jan 26 '12 at 09:14

3 Answers3

5

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:

Community
  • 1
  • 1
Tomasz Nurkiewicz
  • 334,321
  • 69
  • 703
  • 674
3

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.

Alex Barnes
  • 7,174
  • 1
  • 30
  • 50
0

this is actually a question about nested transaction (http://en.wikipedia.org/wiki/Nested_transaction). with spring, (assume you are using version 3 and annotation), REQUIRED is default for transaction mode. If you set this model for your service methods, all methods wrapped by your "wrapper" service will use the host transaction, which means they will run in same transaction.

Kent
  • 189,393
  • 32
  • 233
  • 301