Where does the @Transactional annotation belong?
In general I agree with the others stating that transactions are usually started on the service level (depending on the granularity that you require of course).
However, in the mean time I also started adding @Transactional(propagation = Propagation.MANDATORY)
to my DAO layer (and other layers that are not allowed to start transactions but require existing ones) because it is much easier to detect errors where you have forgotten to start a transaction in the caller (e.g. the service). If your DAO is annotated with mandatory propagation you will get an exception stating that there is no active transaction when the method is invoked.
I also have an integration test where I check all beans (bean post processor) for this annotation and fail if there is a @Transactional
annotation with propagation other than Mandatory in a bean that does not belong to the services layer. This way I make sure we do not start transactions on the wrong layer.
Transactional Annotations should be placed around all operations that are inseparable.
For example, your call is "change password". That consists of two operations
- Change the password.
- Audit the change.
- Email the client that the password has changed.
So in the above, if the audit fails, then should the password change also fail? If so, then the transaction should be around 1 and 2 (so at the service layer). If the email fails (probably should have some kind of fail safe on this so it won't fail) then should it roll back the change password and the audit?
These are the kind of questions you need to be asking when deciding where to put the @Transactional
.
I think transactions belong on the service layer. It's the one that knows about units of work and use cases. It's the right answer if you have several DAOs injected into a service that need to work together in a single transaction.