如何使用Glassfish 2.1在JPA中实现悲观锁定?

时间:2009-09-10 20:14:40

标签: java jpa locking glassfish java-ee-5

尝试设置锁定(悲观)时,使用以下代码:

em.lock(controlnumbers, LockModeType.WRITE);
em.refresh(controlnumbers);

我收到以下异常:

[#|2009-09-10T15:42:48.324-0400|INFO|sun-appserver2.1|javax.enterprise.system.container.ejb|_ThreadID=31;_ThreadName=httpSSLWorkerThread-8080-19;|
javax.ejb.TransactionRolledbackLocalException: Exception thrown from bean; nested exception is: javax.persistence.PersistenceException: ejb30-wrong-lock_called_without_version_locking-index (There is no English translation for this message.)
javax.persistence.PersistenceException: ejb30-wrong-lock_called_without_version_locking-index (There is no English translation for this message.)
        at oracle.toplink.essentials.internal.ejb.cmp3.base.EntityManagerImpl.lock(EntityManagerImpl.java:619)
        at com.sun.enterprise.util.EntityManagerWrapper.lock(EntityManagerWrapper.java:582)
        at com.eximtechnologies.transactionserver.persistence.session.ControlNumbersFacade.lock(ControlNumbersFacade.java:43)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)

如何使用Glassfish 2.1实现悲观锁定?

2 个答案:

答案 0 :(得分:2)

有一种Toplink Essentials(GF 2.1默认)具体方法:

public MyObject lock (MyObject controlnumbers) {
    String qStr = "select object(o) from MyObject as o where o.pk = :pk";
    Query q = em.createQuery(qStr);
    q.setParameter("pk", "a");
    q.setHint("toplink.pessimistic-lock", "Lock");
    controlnumbers = (MyObject)q.getSingleResult();
    return controlnumbers;
}

我相信使用Hibernate调用em.lock实际上会有效。

答案 1 :(得分:0)

你能展示你班级的地图吗?看起来你错过了一个版本属性......看看

http://en.wikibooks.org/wiki/Java_Persistence/Locking#Timestamp_Locking

问候,Jan