I understand that if we use annotation @Transactional. "save()" method is not necessary. Is it exact?
And for my example:
@Transactional
void methodA() {
...
ObjectEntity objectEntity = objectRepository.find();
methodB(objectEntity);
}
void methodB(ObjectEntity obj) {
...
obj.setName("toto");
objectRepository.save(obj); <-- is it necessary?
}
Thanks for your help
It works like following:
save()
attaches the entity to the session and at the end of the transaction as long as there were no exceptions it will all be persisted to the database.
Now if you get the object from the DB (e.g. ObjectEntity objectEntity = objectRepository.find();
) then that object is already attached and you don't need to call the save() method.
If the object, however, is detached (e.g. ObjectEntity objectEntity = new ObjectEntity();
) then you must use the save() method in order to attach it to the session so that changes made to it are persisted to the DB.