Below is the flow of my application
Controller - services - repository
At the service layer we have @Transactional
annotation
We also have jpa:repository
configuration where we specify the entity manager and txn manager.
My doubt is I feel that the txn manager specified in jpa:repositories
is considered and there is no impact of specifying @Transactional
at service layer.
For eg : the service layer @Transactional
can be mapped to custom txn manager where as the repository invoked by the service may have a different txn manager. In that case won't it create a problem?
Can Somebody clarify do we ever need to put @Transactional
at service layer when we are using jpa repository ?
The @Transactional annotation is the metadata that specifies the semantics of the transactions on a method. We have two ways to rollback a transaction: declarative and programmatic. In the declarative approach, we annotate the methods with the @Transactional annotation.
Annotation Type Transactional. Describes a transaction attribute on an individual method or on a class. When this annotation is declared at the class level, it applies as a default to all methods of the declaring class and its subclasses.
Spring Boot and Spring Data JPA make the handling of transactions extremely simple. They enable you to declare your preferred transaction handling and provide seamless integration with Hibernate and JPA. The only thing you need to do is to annotate one of your methods with @Transactional.
REQUIRED is the default setting of a @Transactional annotation. The REQUIRED propagation can be interpreted as follows: If there is no existing physical transaction, then the Spring container will create one.
See section 2.3 of the Spring Data Reference:
http://docs.spring.io/spring-data/jpa/docs/1.0.0.M1/reference/html/#transactions
CRUD methods on your repository are transactional by default. While these transactions can be configured as required, it is normally the case, as suggested in the comments above, that transactions be specified at the Service layer and in that case:
The transaction configuration at the repositories will be neglected then as the outer transaction configuration determines the actual one used.
So, in answer to your question, transactions can (and should be) specified at the service level regardless of any Spring Data transaction management.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With