Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SpringBoot JPA need no .save() on @Transactional? [duplicate]

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?

like image 996
Gregor Sklorz Avatar asked Oct 12 '17 11:10

Gregor Sklorz


People also ask

What does @transactional do in JPA?

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.

What is the difference between save and saveAndFlush in JPA?

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.

Does @transactional lock table Spring?

"@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.

How do I save a JPA Repository?

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.


1 Answers

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.

like image 85
Maciej Kowalski Avatar answered Sep 28 '22 13:09

Maciej Kowalski