7

I am working on a spring-boot project.

Before using @Transactional annotation in my project I have two questions

  1. Best practice to use @Transactional annotation in spring-boot, service layer or DAO layer?

  2. If the service layer then where do I use the @Transactional annotation on a class or on a method in that class?

Ori Marko
  • 56,308
  • 23
  • 131
  • 233
  • Possible duplicate of https://stackoverflow.com/questions/1079114/where-does-the-transactional-annotation-belong & https://stackoverflow.com/questions/26491688/where-should-we-use-transactional-and-where-is-service-layer – DEBENDRA DHINDA May 02 '19 at 09:26
  • @DEBENDRADHINDA 2 question isn't answered,actually there are 2 upvoted answers with both cases – Ori Marko May 02 '19 at 10:50

2 Answers2

4
  1. in the service layer: you want your whole business method to be ACID
  2. on the class if you want all bean methods to be transactional, on the method if you want that specific method to be transational, or to have different transactional attributes
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
4
  1. Use @Transactional in Service layer because DAO layer shouldn't include business logic

Service layer may call different DAO to perform DB operations. Lets assume a situations where you have 3 DAO operations in a service method. If your 1st DAO operation failed, other two may be still passed and you will end up inconsistent DB state. Annotating Service layer can save you from such situations.

  1. Use it in method level, because class level is less useful, because it forces all methods (and future methods/sub classes) to be transactional

At the class level, this annotation applies as a default to all methods of the declaring class and its subclasses

Ori Marko
  • 56,308
  • 23
  • 131
  • 233
  • @Transactional annotation applies on the class level but It gives an error "org.hibernate.AssertionFailure: possible non-threadsafe access to the session" There is trigger applied on my database table. – Shaha Nawaj Mulla May 10 '19 at 12:50
  • @ShahanawajMulla please ask a new question with relevant code – Ori Marko May 12 '19 at 08:51