我只是在尝试乐观锁定.
我有以下课程:
@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]
还行吧.
我的问题是:@H_301_21@1)如果我希望第二个事务什么也不做,并且不抛出任何异常,我该怎么办?
2)如果我希望第二个事务覆盖第一个事务更新的数据,我该怎么办?
谢谢.