1.
hibernate基于数据版本(Version)记录机制实现。为数据增加一个版本标识,一般是通过为数据库表增加一个“version”字段来实现。读取出数据时,将此版本号一同读出,之后更新时,对此版本号加一。此时,将提交数据的版本数据与数据库表对应记录的当前版本信息进行比对,如果提交的数据版本号大于数据库表当前版本号,则予以更新,否则认为是过期数据。
2. 例子:
//$Id: Conductor.java 11282 2007-03-14 22:05:59Z epbernard $
package org.hibernate.test.annotations.various;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Version;
import org.hibernate.annotations.Index;
import org.hibernate.annotations.OptimisticLock;
/**
* @author Emmanuel Bernard
*/
@Entity
public class Conductor {
@Id
@GeneratedValue
private Integer id;
@Column(name = "cond_name")
@Index(name = "cond_name")
//@OptimisticLock(excluded = true)
private String name;
@Column(name = "cond_address")
@Index(name = "cond_address")
@OptimisticLock(excluded = true)
private String address;
@Version
private Long version;
}
address是本人加上的.同时省略了get set方法.
测试:
//$Id: IndexTest.java 11282 2007-03-14 22:05:59Z epbernard $
package org.hibernate.test.annotations.various;
...........................
/**
* @author Emmanuel Bernard
*/
public class IndexTest extends TestCase {
...............
@SuppressWarnings("unchecked")
public void testVersion() throws Exception {
Session session1=openSession();
Session session2=openSession();
Conductor stu1=(Conductor)session1.createQuery("from Conductor as a where a.name='Bob'").uniqueResult();
Conductor stu2=(Conductor)session2.createQuery("from Conductor as a where a.name='Bob'").uniqueResult();
//这时候,两个版本号是相同的
System.out.println("v1="+stu1.getVersion()+"--v2="+stu2.getVersion());
Transaction tx1=session1.beginTransaction();
stu1.setName("session1");
tx1.commit();
//这时候,两个版本号是不同的,其中一个的版本号递增了
System.out.println("v1="+stu1.getVersion()+"--v2="+stu2.getVersion());
Transaction tx2=session2.beginTransaction();
stu2.setName("session2");
tx2.rollback();
session2.close();
session1.close();
}
............
}
添加testVersion方法。