![](/img/trans.png)
[英]Is it a good convention to define save method inside hibernate/jpa entity class?
[英]Is it a good or bad convention to update entity / row without calling save() in hibernate / spring-jpa?
最近我发现如果在@Transactional
块中,没有必要调用repository.save()
。 Hibernate / Spring-JPA 将在退出事务时自动更新行。 例如
@Transactional
public updateName(Long id, String name) {
User user = repository.findOneById(id);
user.setName(name);
// repository.save(user); // <- looks not necessary?
}
这是一个好的或坏的约定? 恐怕有时@Transactional
在某些特殊情况下不起作用。
有时如果没有调用其他更新方法,Hibernate 上下文将不会执行保存操作。 调用 save 方法总是更好。
为什么你认为@Transactional
不会“工作”? 您正在利用该实体在 JPA 术语中是“托管”的事实,所以这完全没问题。 事实上,使用save
甚至可能导致不必要的操作,因为 Hibernate 必须同步持久化上下文。 如果您在事务中有其他操作,一次执行所有操作可能更有效,所以我不建议调用 save 除非您真的希望 state 同步。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.