How to use @Transactional annotation in Spring boot

4.8k Views Asked by At

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?

2

There are 2 best solutions below

0
JB Nizet On
  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
2
Ori Marko On
  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