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?
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
orupdate
methods.save
orpersist
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
orevict
methods on that particular entity before those changes occur.