Anu*_*pta 7 java hibernate locking optimistic-locking
我是Hibernate和Spring的新手,在尝试学习Spring,Hibernate,Maven等时,我只知道如何使用所有这三个来运行一个hello world示例.基于我的基本理解,我被分配了一个执行乐观锁定的任务.据我搜索它,我只能看到我所需要的是在我的映射类中的xml和整数变量版本中添加版本标签并不是很困难.就像这样...
public class MyClass {
...
private int version;
...
}
Run Code Online (Sandbox Code Playgroud)
我的xml应该是这样的
<class name="MyClass">
<id ...>
<version name="version" column="VERSION" access="field">
...
</class>
Run Code Online (Sandbox Code Playgroud)
当第二个用户保存时,hibernate将自动处理版本控制,hibernate发现此用户正在处理陈旧数据并抛出StaleObjectException.
只是想提前确认我的理解.
如果有人可以为我指出一个问候世界的例子,那将会非常有帮助.
我还想提一下,我正在尝试实施"最后提交胜利"的场景
Ser*_*nko 11
我使用了Hibernate注释,这是我对乐观锁定的实现
@Entity
public class MyObject {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String data;
@Version
private Integer version; // this is version field
}
Run Code Online (Sandbox Code Playgroud)
这是一个有效的例子
// 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;
}
Run Code Online (Sandbox Code Playgroud)
还有一些代码可以向DB添加一个元素
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();
Run Code Online (Sandbox Code Playgroud)
创建后,DB中的新元素具有版本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;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
17073 次 |
| 最近记录: |