简体   繁体   中英

How to set-up transactions for both the web application and batch jobs using Spring and Hibernate

I have an application which uses Spring 4.3 and Hibernate 5.3.

There's a web application with a presentation layer, a servive layer and a DAO layer, as well as some jobs sharing the same service and DAO layers.

Transactions are initialized in different layers with @Transactional annotations.

It led me to a problem I described here: Controlling inner transaction settings from outer transaction with Spring 4.3

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?

Pardon me for replying in answer as I am not able to comment

I don't get the meaning of you having to keep initializing transactions from the jobs?

Usually for

  • DAO class, it should be annotated with @Repository .
  • Service class with @Service and @Transactional
  • Webservice, if u have, with @RestController , @RequestMapping , @Transactional .

By doing so, any call from service class will be 1 transaction thus if Service class A calls service B and C, even if service class C throws error, the whole transactions will be rollback.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM