gpt4 book ai didi

java - Spring Hibernate 保存/提交事务而不调用 Save 方法

转载 作者:行者123 更新时间:2023-12-02 05:02:39 24 4
gpt4 key购买 nike

我正在使用 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

引自the documentation

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com