I have an application which uses Spring 2.5 and Hibernate 3.
There’s a web application with a presentation layer, a servive layer and a DAO layer, as well as some Quartz jobs sharing the same service and DAO layers.
Transactions are initialized in different layers with @Transactional annotations, like this:

It led me to a problem I described here: Controlling inner transaction settings from outer transaction with Spring 2.5
I read a bit about how to set-up transactions to wire Spring and Hibernate together. It looks the recommended approach is to initialize transactions in the service layer.
What I don’t like is that most transactions exist only because they are required for hibernate to work properly.
And when I really need a transaction for a job calling multiple service methods, it seems I don’t have a choice to keep initializing transactions from the jobs. So moving @Transactional annotations from DAO to service doesn’t seem to make any difference.
How would you recommend to set-up transactions for this kind of application?
Definitely. Transaction demarcation should be done at the service layer level, not at the DAO layer level:
You should maybe elaborate this part because transactions are not Hibernate specific.
If you want to call multiple services inside a transaction initiated from the Job layer, declare your services as transactional with
REQUIREDsemantics (the default) and rely on Spring transaction propagation (this applies unless you need a remote call; in that case, use EJBs).It does make a difference and the fact that you need to initiate transactions from the Job layer when running batches doesn’t make things different.
I warmly recommend to read the Chapter 9. Transaction management.
No problem. It’s just that when a question is vague, you often get a vague answer 🙂
Sorry but the above statement only says that the “communication with a database has to occur inside a transaction”, nothing more, and deciding where to start transaction is left at your discretion (typically the service layer). If you do it at the DAO level, what if
MySuperServicecallsDaoFooandDaoBarandDaoBarfails? In such cases, you’ll probably want to rollback all the changes, not only those performed inDaoBar. Hence the need to control transaction where the unit of work starts.IMHO, the developers need some guidance.
First of all, I suggest to read Non-transactional data access and the auto-commit mode (the little brother of Sessions and transactions) to clarify things about “read-only transactions”. Reading the whole page is worth it but let me just quote this specific part:
Once you’ll be done with the above link, the next suggested reading will be @Transactional read-only flag pitfalls. Here is the relevant part: