Hibernate学习:乐观锁version

一:程序


二:分析


1:在实体中增加字段version

@Version
private int version;


2:Account a1 = (Account) session1.load(Account.class, 1);

Account a2 = (Account) session2.load(Account.class, 1);

version默认为0

 当session1.getTransaction().commit();version字段增加1,从0变成1

当session2.getTransaction().commit(); 原来获取的version是0,但是现在数据库已经完成1,不匹配,就会报错


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



 
 
 

你可能感兴趣的:(Hibernate,乐观锁)