注意:要在user表中增加一个字段:version int
User.hbm.xml
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
OptimisticlLockingTest.java
package com.shiryu.otm;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.criterion.Expression;
//乐观锁 Optimistic Lock
public class OptimisticLockingTest {
public static void main(String[] args) {
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
Session session = sessionFactory.openSession();
Criteria criteria = session.createCriteria(User.class);
criteria.add(Expression.eq("name", "zhaiyu"));
List l = criteria.list();
User user = (User) l.get(0);
Transaction tr = session.beginTransaction();
user.setAge(21);// 更新age字段
tr.commit();
session.close();
// 每次对数据库进行更新时,数据库中version都在递增
// 现在我们尝试在tr.commit之前,启动另外一个Session,对zhaiyu用户进行操作,模拟并发时的情景
Session session1 = sessionFactory.openSession();
Criteria criteria1 = session1.createCriteria(User.class);
criteria1.add(Expression.eq("name", "zhaiyu"));
Session session2 = sessionFactory.openSession();
Criteria criteria2 = session2.createCriteria(User.class);
criteria2.add(Expression.eq("name", "zhaiyu"));
List userList1 = criteria1.list();
List userList2 = criteria2.list();
User user1 = (User) userList1.get(0);
User user2 = (User) userList2.get(0);
Transaction tr1 = session1.beginTransaction();
Transaction tr2 = session2.beginTransaction();
user1.setAge(26);// 更新age字段
tr1.commit();
user2.setAge(44);// 更新age字段
tr2.commit();// 系统出现StaleObjectStateException异常,并指出版本检测失败
}
}