繁体   English   中英

如何在hibernate中做乐观锁定

[英]How to do optimistic locking in hibernate

我是Hibernate和Spring的新手,在尝试学习Spring,Hibernate,Maven等时,我只知道如何使用所有这三个来运行一个hello world示例。 基于我的基本理解,我被分配了一个执行乐观锁定的任务。 据我搜索它,我只能看到我所需要的是在我的映射类中的xml和整数变量版本中添加版本标签并不是很困难。就像这样...

public class MyClass {
...
private int version;
...
}

我的xml应该是这样的

<class name="MyClass">
<id ...>
<version name="version" column="VERSION" access="field">
...
</class>

当第二个用户保存时,hibernate将自动处理版本控制,hibernate发现此用户正在处理陈旧数据并抛出StaleObjectException。

只是想提前确认我的理解。

如果有人可以为我指出一个问候世界的例子,那将会非常有帮助。

我还想提一下,我正在尝试实施“最后提交胜利”的场景

我使用了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;
}

还有一些代码可以向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();

创建后,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;
    }
}

如果我们使用xml样式,我们可以在hbm文件中使用如下:

<id name="productId" column="pid"  />
**<version name="v" column="ver" />**
<property name="proName" column="pname" length="10"/>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM