简体   繁体   中英

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

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM