'@Transactional spring JPA .save() not necessary?
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
Solution 1:[1]
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.
Solution 2:[2]
[It is a little too late, but I hope it would be helpful to future readers]:
Within a transaction context, an update to a managed instance is reflected in the persistence storage at the commit/flush time, i.e., in your case at the end of methodB()
. However, calling save()
comes with a cost in scenarios like yours, as stated in Spring Boot Persistence Best Practices:
The presence or absence of save() doesn’t affect the number or type of queries, but it still has a performance penalty, because the save() method fires a MergeEvent behind the scenes, which will execute a bunch of Hibernate-specific internal operations that are useless in this case. So, in scenarios such as these, avoid the explicit call of the save() method.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | catch23 |
Solution 2 | Shahin |