2012-02-18 61 views
13

這裏發生了什麼?實體必須設法調用刪除

@Stateless 
@LocalBean 
public class AppointmentCommentDao { 
    public void delete(long appointmentCommentId) { 
     AppointmentComment ac = em.find(AppointmentComment.class, appointmentCommentId); 
     if (ac != null) 
     { 
      em.merge(ac); 
      em.remove(ac); 
     } 
    } 
    @PersistenceContext 
    private EntityManager em; 
} 

在調用remove我得到一個IllegalArgumentException與消息是Entity must be managed to call remove: ...., try merging the detached and try the remove again.

+0

與em.find(...)方法解決了這個問題。 – 2015-10-07 13:18:37

回答

18

在你的情況的合併是不需要的,因爲交流是沒有任何一點em.findEM之間deattached .remove

通常,當實體deattached,EntityManager的方法合併需要實體作爲參數,收益管理的實例。作爲參數給出的實體不會被轉換爲被附加。這例如在這裏解釋:EntityManager.merge。你必須去的:

AppointmentComment toBeRemoved = em.merge(ac); 
    em.remove(toBeRemoved); 
+0

奇怪...沒有改變那個代碼(雖然還有其他不相關的變化),但它神祕地開始工作。我甚至完全取消了合併,因爲我首先得到它的全部原因是我得到了這個例外。它不應該是必須的,因爲當我們處於加載它的同一個持久化上下文中時,實體應該被連接。我想其他事情正在發生。愚蠢的GlassFish。 – 2012-02-18 07:02:07

+0

不過,我確實接受你的觀點,你應該使用從前向合併中返回的對象,而不是傳入的對象。 +1 – 2012-02-18 07:02:48

+0

你是絕對正確的,你的代碼應該沒有合併工作,因爲ac在任何時候都沒有脫離。我首先認爲這是一個過於簡單的例子。我會更新答案。 – 2012-02-18 09:10:59

6

試試這個:

entity = getEntityManager().getReference(AppointmentComment.class, entity.getId()); 
getEntityManager().remove(entity);