Shaha Nawaj Mulla
Shaha Nawaj Mulla

Reputation: 171

How to use @Transactional annotation in Spring boot

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?

Upvotes: 7

Views: 4956

Answers (2)

Ori Marko
Ori Marko

Reputation: 58774

  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

Upvotes: 4

JB Nizet
JB Nizet

Reputation: 691635

  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

Upvotes: 4

Related Questions