Spring @Transactional Annotation Best Practice
We are currently discussing the Best Practice for placing the @Transactional annotations in our code.
Do you place the @Transactional in the DAO classes and/or their methods or is it better to annotate the Service classed which are calling using the DAO objects? Or does it make sense to annotate both "layers"?
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.
The normal case would be to annotate on a service layer level, but this really depends on your requirements.
Annotating on a service layer will result in longer transactions than annotating on DAO level. Depending on the transaction isolation level that can youse problems, as concurrent transactions wont see each other's changes in eg. REPEATABLE READ.
Annotating on the DAOs will keep the transactions as short as possible, with the drawback that the functionality your service layer is exposing wont be done in a single (rollbackable) transaction.
It does not make sense to annotate both layers if the propagation mode is set to default.