我正在尝试学习乐观的并发控制。
以下计划
我收到以下异常: 线程“main”中的异常org.hibernate.StaleObjectStateException:Row被另一个事务更新或删除(或unsaved-value映射不正确):[com.raj.hibernate.optimistic.OptPerson#1]
请告诉我
session.merge会帮助我吗。
final SessionFactory factory = new Configuration().configure()
.buildSessionFactory();
Session session = factory.openSession();
session.beginTransaction();
OptPerson optP1 = new OptPerson();
optP1.setName("raj");
session.save(optP1);
session.getTransaction().commit();
session.close();
System.out.println("done saving, closed session");
new Thread() {
public void run() {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Session session2 = factory.openSession();
session2.beginTransaction();
OptPerson p1 = (OptPerson) session2.get(OptPerson.class, 1);
p1.setName("raj10");
session2.save(p1);
session2.getTransaction().commit();
session2.close();
System.out.println("modified person in session2");
}
}.start();
Session session3 = factory.openSession();
session3.beginTransaction();
OptPerson p1 = (OptPerson) session3.get(OptPerson.class, 1);
System.out.println("read person in session3");
Thread.sleep(8000);
try {
p1.setName("man");
session3.save(p1);
session3.getTransaction().commit();
} catch (StaleObjectStateException ex) {
System.out.println("inside catch block");
OptPerson p3 = (OptPerson) session3.get(OptPerson.class, 1);
p3.setName("man");
session3.saveOrUpdate(p3);
//OptPerson p4 = (OptPerson) session3.merge(p1);
session3.getTransaction().commit();
} finally {
session3.close();
}