</hibernate-mapping>
注意 version 节点必须出现在 ID 节点之后。
这里我们声明了一个 version 属性,用于存放用户的版本信息,保存在 User 表的version中
optimistic-lock 属性有如下可选取值:
Ø none
无乐观锁
Ø version
通过版本机制实现乐观锁
Ø dirty
通过检查发生变动过的属性实现乐观锁
Ø all
通过检查所有属性实现乐观锁
其中通过 version 实现的乐观锁机制是 Hibernate 官方推荐的乐观锁实现,同时也
是 Hibernate 中,目前唯一在数据对象脱离 Session 发生修改的情况下依然有效的锁机
制。因此,一般情况下,我们都选择 version 方式作为 Hibernate 乐观锁实现机制。
public class UserTest {
public static void main(String[] args) {
Configuration conf=new Configuration().configure();
SessionFactory sf=conf.buildSessionFactory();
Session session=sf.openSession();
// Session session2=sf.openSession();
User user=(User) session.createQuery(" from User user where user=5").uniqueResult();
// User user2=(User) session.createQuery(" from User user where user=5").uniqueResult();
System.out.println(user.getVersion());
// System.out.println(user2.getVersion());
Transaction tx=session.beginTransaction();
user.setUserName("101");
tx.commit();
public class UserTest2 {
public static void main(String[] args) throws InterruptedException {
Configuration conf=new Configuration().configure();
SessionFactory sf=conf.buildSessionFactory();
Session session=sf.openSession();
// Session session2=sf.openSession();
User user=(User) session.createQuery(" from User user where user=5").uniqueResult();
Thread.sleep(10000);
// User user2=(User) session.createQuery(" from User user where user=5").uniqueResult();
System.out.println(user.getVersion());
// System.out.println(user2.getVersion());
Transaction tx=session.beginTransaction();
user.setUserName("100");
tx.commit();
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Exception in thread "main" org.hibernate.StaleObjectStateException: Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect): [com.xiaohao.test.User#5]
at org.hibernate.persister.entity.AbstractEntityPersister.check(AbstractEntityPersister.java:1932)
at org.hibernate.persister.entity.AbstractEntityPersister.update(AbstractEntityPersister.java:2576)
at org.hibernate.persister.entity.AbstractEntityPersister.updateOrInsert(AbstractEntityPersister.java:2476)
at org.hibernate.persister.entity.AbstractEntityPersister.update(AbstractEntityPersister.java:2803)
at org.hibernate.action.EntityUpdateAction.execute(EntityUpdateAction.java:113)
at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:273)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:265)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:185)
at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:321)
at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:51)
at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1216)
at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:383)
at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:133)
at com.xiaohao.test.UserTest2.main(UserTest2.java:21)