我正在使用 JPA 的 Spring 和 Hibernate 实现。 在我的服务类中,我有一个方法如下。
@Override
public String myMethod(String arg) throws Exception {
MyObject obj = fetchFromDB();
// Some code to update object.
if(isSuccess){
myObject.saveAndFlush();
}
else{
return failure;
}
}
由于某种原因,即使我没有保存对象,更改也会保存到数据库中。
最佳答案
当您从数据库获取对象时,它附加到 hibernate session 。您对附加对象所做的每个更改都会保留,无需在对象上显式调用 save
。
Hibernate will detect any changes made to an object in persistent state and synchronize the state with the database when the unit of work completes.
就您而言,如果可能的话,您应该对 isSuccess
block 内的对象进行所有更新。
关于java - Spring Hibernate 保存/提交事务而不调用 Save 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28101263/