'Is it a good or bad convention to update entity / row without calling save() in hibernate / spring-jpa?

Recently I found it not necessary to call repository.save() if within a @Transactional block. Hibernate / Spring-JPA will update row automatically when exiting transaction. e.g.

@Transactional
public updateName(Long id, String name) {
    User user = repository.findOneById(id);
    user.setName(name);
    // repository.save(user); // <- looks not necessary?
}

Is it a good or bad convention? I'm afraid sometimes @Transactional doesn't work in some special conditions.



Solution 1:[1]

Why do you think would @Transactional not "work"? You are making use of the fact that the entity is "managed" in JPA terms, so that is totally fine. In fact, using save might even cause unnecessary operations as Hibernate has to synchronize the persistence context. It might be more efficient to do all operations, in case you have other operations in the transaction, at once, so I would not recommend calling save unless you really want the state to be synchronized.

Solution 2:[2]

Sometimes if no other update method is called, the Hibernate context will not perform a save operation. it's always better to call the save method.

Solution 3:[3]

my understanding is that on transaction finish will be saved to DB all managed entities in JPA persistent context. It means that entities NOT managed will not be saved, e.g. new entities created by new operator (not read from DB, because all entities read from DB are managed ). I think save() must be used only for non managed entities. For managed entities it may be more efficient to NOT call save().

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 Christian Beikov
Solution 2 Thomson Ignesious
Solution 3 st100