Reputation: 464
This link: https://www.quora.com/When-should-Spring-Boot-methods-use-the-Transactional-annotation
Explain clearly what's @Transactional doing, but I still don't understand when should Spring Boot methods use this annotation:
For example:
I have this method:
void addPerson () {// code that calls the DAO layer}
My method will work well without the @Transactional annotation then why i should add this annotation.
More precisely (in spring boot) what's the difference between:
@Transactional void addPerson () {// code that calls the DAO layer}
and
void addPerson () {// code that calls the DAO layer}
Or does Spring boot add automatically this annotation so we don't need to add it to our services
Upvotes: 5
Views: 8662
Reputation: 73
By default SpringBoot sets the spring.jpa.open-in-view
property to true
value, that means Spring automatically makes a transaction for each request.
If you set this property to false
, you must annotate with @Transactional
the point where you want to initialize it [Controller|Service|DAO].
Upvotes: -1
Reputation: 477
You use @Transcational
when concurrent calls on your API can affect each other.
Let's say you want to add a Person (you retreive data from somewhere, create a new Person from data and add it to a list of persons). Let's assume in order to create a Person you need a partner
attribute which is another Person.
Before creating a Person you would search the partner by Id somehwere and add it to the new Person partner
attribute. But what if during all this Queries the partner
you wanted to add is deleted somewhere (let's say in the database due to some other query). You'll end up not having the object you requested.
If you use @Transactional
Spring makes sure all the required data is safe until the Transaction ends. Once it ends, the delete request from the partner
would take place and then you'll have some logic to remove it from the new Person object. But that would take place afterwards.
You use @Transactional
to ensure safety on your "Transactions".
Upvotes: 12