2016-01-21 160 views
1

我有OptimisticLockException,因爲當用戶從diffrenet瀏覽器選項卡兩次同時點擊保存按鈕兩次以下代碼(錯誤代碼:entity = em.merge(entity);)。 注意:entity.getOid()不爲null! 誰可以幫我...如何處理JPA中的OptimisticLockException

public static synchronized KirKiraciSozlesmeYeniKayitForm kaydet(KirKiraciSozlesmeYeniKayitForm form, EntityManager em) { 

    KirKiraciSozlesme entity = new KirKiraciSozlesme(); 
    UtilInsCore.copyProperties(form, entity); 

    if (entity.getOid() == null) { 
     Long oid = DBUtil.getSeqNextValue(em, "KIR_KIRACI_SOZLESME_SEQ"); 
     entity.setOid(oid); 
    } 
    entity = em.merge(entity); 
    em.flush(); 
    UtilInsCore.copyProperties(entity, form); 

    return form; 
} 

預先感謝您。

+0

問題是什麼? – brito

+0

我需要解決方案這種情況 –

回答

1

這是正確的JPA行爲。 當用戶點擊保存按鈕時,第一次實體版本字段增加。所以當用戶點擊保存按鈕時,第二個標籤版本不同,並且JPA生成樂觀鎖定異常。 如果用戶在第一個選項卡中更改field1並將其保存並將field2更改爲第二個選項卡並將其保存爲無樂觀例外,那麼實體狀態會是什麼? 您可以通知用戶,第二次該實體已被另一個用戶更改並重新加載新的實體狀態或類似的東西...

+0

根據我的研究,這是正確的JPA行爲。在這種情況下,我應該給catch塊留言。 謝謝 –

0

嘗試在你的代碼添加爲:

... 
em.lock(entity, LockModeType.PESSIMISTIC_WRITE); 

    if (entity.getOid() == null) { 
      Long oid = DBUtil.getSeqNextValue(em, "KIR_KIRACI_SOZLESME_SEQ"); 
      entity.setOid(oid); 
     } 
     entity = em.merge(entity); 

     em.getTransaction().commit();//To unlock the Entity 
... 

希望這有助於。

+0

oo對不起,我不解決。感謝 –

+0

爲什麼用戶想要做一個PESSIMISIC鎖,當問題是關於OPTIMISTIC? –