gpt4 book ai didi

java - 乐观锁定和 org.hibernate.StaleObjectStateException :

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:03:39 25 4
gpt4 key购买 nike

我只是在尝试乐观锁定。

我有以下类(class):

@Entity
public class Student {

private Integer id;
private String firstName;
private String lastName;
private Integer version;
@Version
public Integer getVersion() {
return version;
}

//all other getters ommited.
}

现在我正在获取其中一名学生并尝试同时更新其属性。

Thread t1 = new Thread(new MyRunnable(id));
Thread t2 = new Thread(new MyRunnable(id));
t1.start();
t2.start();

在 MyRunnable 内部:

public class MyRunnable implements Runnable {
private Integer id;
@Override
public void run() {
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
Student student = (Student) session.load(Student.class, id);
student.setFirstName("xxxx");
session.save(student);
session.getTransaction().commit();
System.out.println("Done");
}

public MyRunnable(Integer id){
this.id = id;
}
}

第一个事务成功更新对象和第二个事务抛出发生了什么:

org.hibernate.StaleObjectStateException: Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect): [com.vanilla.entity.Student#1]

没关系。

我的问题是:1)如果我想让第二个事务什么都不做,不抛出任何异常怎么办?

2) 想让第二个事务覆盖第一个事务更新的数据怎么办?

谢谢。

最佳答案

我试着回答你的问题:

  1. 您使用乐观锁定。因此,您希望在版本冲突时抛出 OptimisticLockException - 但您可以捕获它而不做任何操作。你不能将它关闭第二个(无论那意味着什么)事务,因为你不知道是否会发生版本冲突(这是乐观锁策略的本质:乐观假设是版本冲突不会经常发生)

  2. 如果发生 OptimisticLockException,您基本上有 2 个选择:

    1. 放弃更改(并可能刷新当前状态)
    2. 仅刷新您的实体版本并尝试再次提交

    问题是如果您有并发更新,如何或由谁来决定哪个状态是实际的“正确”(意味着最新)状态。只要保证一致性,我不在乎。

关于java - 乐观锁定和 org.hibernate.StaleObjectStateException :,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7664768/

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