我使用了 Hibernate 注释,这是我的乐观锁定实现
@Entity
public class MyObject {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String data;
@Version
private Integer version; // this is version field
}
这是工作示例
// Entity class with version field
@Entity
public class Ent1 implements Serializable {
private static final long serialVersionUID = -5580880562659281420L;
@Id
Integer a1;
Integer a2;
@Version
private Integer version;
}
以及一些将一个元素添加到数据库的代码
session = HibernateHelper.getSessionFactory().openSession();
transaction = session.beginTransaction();
Ent1 entity = new Ent1();
entity.setA1(new Integer(0));
entity.setA2(new Integer(1));
session.save(entity);
transaction.commit();
// get saved object and modify it
transaction = session.beginTransaction();
List<Ent1> list = (List<Ent1>)session.createQuery("FROM Ent1 WHERE a1 = 0").list();
Ent1 ent = list.get(0);
ent.setA2(new Integer(1000));
session.save(ent);
transaction.commit();
创建后,数据库中的新元素的版本为 0。修改后 - 版本 1。
HibernateHelper.java
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
public class HibernateHelper {
private static final SessionFactory sessionFactory;
static {
try {
sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
} catch (Throwable ex) {
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}