6

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

YannaY
  • 105
  • 2
  • 9
  • In this particular case (when operating existing entity within same Session) it's not necessary, since `@Transactional` under the hood saves and flushes all changes to managed entities to DB – Nikolai Shevchenko Apr 27 '20 at 14:01

2 Answers2

11

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.

catch23
  • 17,519
  • 42
  • 144
  • 217
InsertKnowledge
  • 1,012
  • 1
  • 11
  • 17
1

[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.

Shahin
  • 253
  • 1
  • 3
  • 13