在事务中两次持久化同一实体时出错

Error on persisting same entity twice within a transaction

考虑数据库中存在的实体。 以下操作发生在事务中 -

mainfuntion()
{
    transaction.begin();
    function1();
    if(check some business logic )
    {
        function2()
    }
    transaction.commit()
}
function1()
{
    query1 - returns Entity
    modify Entity;
    EntityManager.persist(Entity)
}
function2()
{
    query1 - returns Entity
    modify Entity
    EntityManager.persist(Entity)
}

现在发生的两个修改在逻辑上分开是有意义的,因此我不想将这两个修改组合在一起。我也不想在两种方法之间传递实体。

提交时出现以下异常 -

org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1

谁能告诉我怎样才能在没有错误的情况下达到预期的结果?

您是否在您的实体中使用带有 Date/Timestamp 的 @Version 注释? 我过去也遇到过类似的情况。 Hibernate 在尝试使用 @Version 列更新实体时,包括 @Version 列以及更新语句中的主键。

hibernate 文档提到了这一点 -

When using a java.util.Date, instead of a long/Long for the revision timestamp, take care not to store it to a column data type which will loose precision.

这导致第二个更新语句未获取所需的行,因此出现意外的行计数异常。

尝试不使用 @Version 注释或使用 integer/long 版本。