I have short question:
Do I need a repo.save(x)
call on @Transactional
methods?
I ask cause I see changes on my DB without save, and read no clear docs about it.
So is it working as intended, or just a (welcome) unexpected behavior?
example:
@Autowired private UserRepo repo; @Transactional @PutMapping public Long put(@RequestBody User user) { User u = repo.findOne(user.getId()); u.setName("Paul"); repo.save(u); // DO I NEED THIS LINE? }
I'am just unsure about it, so maybe someone can shed some light on the subject?
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.
Save and saveAndFlush both can be used for saving entities. They both are both belong to the Spring data library. save may or may not write your changes to the DB straight away. When we call saveAndFlush system are enforcing the synchronization of your model state with the DB.
"@Transactional" as itself on any isolation level doesn't enabling any locking. To achieve locking behaviour you should use "@Lock" annotation or use " for update" in your query.
save(…)- Method. It will persist or merge the given entity using the underlying JPA EntityManager. If the entity has not been persisted yet Spring Data JPA will save the entity via a call to the entityManager.
If you retrieve an entity, for example using the findOne
method call within a transactional method it has become managed from that point by the persistence provider.
Now if you make any changes to that entity (which is actually a proxy object), upon transaction commit, those changes will be persisted to the database, regardless of the fact of invoking the save
or update
methods.
save
or persist
has to be used when you are creating a new entity from scratch and persistence provider does not know of its existance yet.
Remember that you can prevent making any changes upon commit, if you use detach
or evict
methods on that particular entity before those changes occur.
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