gpt4 book ai didi

java - Jpa 合并抛出 StaleObjectStateException?

转载 作者:行者123 更新时间:2023-12-02 10:38:51 25 4
gpt4 key购买 nike

当我尝试创建四个客户时,有代码。1.将Customer1,2写入数据库2. 合并Customer3(具有相同的id,例如1)3.合并Customer4(再次具有相同的id)我想创建同一实体的任何版本

所以,

public static void main(String[] args) {
EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("Info");
EntityManager entityManager = entityManagerFactory.createEntityManager();

Customer customer1 = new Customer("1", "Vladislav");
Customer customer2 = new Customer("2", "Maria");
Customer customer3 = new Customer("1", "Ekaterina");
Customer customer4 = new Customer("1", "Helen");

entityManager.getTransaction().begin();
entityManager.persist(customer1);
entityManager.persist(customer2);
entityManager.getTransaction().commit();

entityManager.getTransaction().begin();
entityManager.merge(customer3);
entityManager.getTransaction().commit();

entityManager.getTransaction().begin();
entityManager.merge(customer4);
entityManager.getTransaction().commit();

//get versions here:
entityManager = entityManagerFactory.createEntityManager();
AuditReader auditReader = AuditReaderFactory.get(entityManager);
List<Number> versions = auditReader.getRevisions(Customer.class, "1");
System.out.println("========");
System.out.println(Arrays.toString(versions.toArray()));

entityManager.close();
entityManagerFactory.close();
}

客户实体:

package entity;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.hibernate.envers.Audited;

import javax.persistence.*;


@Getter
@Setter
@NoArgsConstructor
@Entity
@Audited
public class Customer {
@Id
@Column(length = 100, nullable = false)
private String id;
private String name;

@Version
int version;

public Customer(String id, String name) {
this.id = id;
this.name = name;
}

@Override
public String toString() {
return "Customer{" +
"id='" + id + '\'' +
", name='" + name + '\'' +
", version=" + version +
'}';
}
}

当我仅保留客户 1,2 并合并客户 3 时 - 一切正常。

但是在我添加与 customer4 实体的合并时 - 出现错误消息 -

线程“main”中出现异常 javax.persistence.OptimisticLockException:行已被另一个事务更新或删除(或未保存值映射不正确):[entity.Customer#1]导致:org.hibernate.StaleObjectStateException:行已被另一个事务更新或删除(或未保存值映射不正确):[entity.Customer#1] ... 2 更多

为什么我每次都无法合并?

最佳答案

您只能将客户与具有最新版本的实例合并。

customer1 具有版本=0

id = '1'的当前版本现在为 0

customer3 具有 version=0,因此可以合并,合并后 version=1

id = '1'的当前版本现在是 1

customer4 具有 version=0,因此无法再进行合并。

关于java - Jpa 合并抛出 StaleObjectStateException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53078560/

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