@Transactional spring JPA .save() 不需要吗?

@Transactional spring JPA .save() not necessary?

我理解如果我们使用注解@Transactional。 "save()" 方法不是必需的。准确吗?

以我为例:

@Transactional
void methodA() {
   ...
   ObjectEntity objectEntity = objectRepository.find(); 
   methodB(objectEntity);
}

void methodB(ObjectEntity obj) {
   ...
   obj.setName("toto");
   objectRepository.save(obj);    <-- is it necessary?
}

感谢您的帮助

它的工作原理如下:

  • save() 将实体附加到会话,并且在事务结束时只要没有异常,它就会全部保存到数据库中。

  • 现在,如果您从数据库中获取对象(例如 ObjectEntity objectEntity = objectRepository.find();),那么 该对象已经附加,您不需要调用 save()方法

  • 但是,如果对象已分离(例如 ObjectEntity objectEntity = new ObjectEntity();),则 您必须使用 save() 方法 才能附加它到会话,以便将对其所做的更改持久保存到数据库中。

[有点晚了,希望对以后的读者有所帮助]:

在事务上下文中,对托管实例的更新会在 commit/flush 时间反映在持久性存储中,即在您的情况下会在 methodB() 结束时反映出来。但是,如 Spring Boot Persistence Best Practices:

所述,在像您这样的情况下调用 save() 会产生费用

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.