2012-07-11 48 views
0

這裏是我的代碼,刪除無外鍵對象JPA控制器

SiteMember類

@OneToMany(mappedBy = "member",cascade=CascadeType.ALL) 
    private List<MemberThread> memberThread = new ArrayList<MemberThread> 

MemberThread類

@ManyToOne(cascade=CascadeType.ALL) 
    @JoinColumn(nullable=false) 
    private SiteMember member; 

MemberThreadJpaController類

public void destroy(Long id) throws IllegalOrphanException, NonexistentEntityException, NotSupportedException, RollbackException, HeuristicMixedException, HeuristicRollbackException, SecurityException, IllegalStateException, SystemException { 
     EntityManager em = null; 
     try { 
      em = getEntityManager(); 
      ut.begin(); 
      MemberThread memberThread; 
      try { 
       memberThread = em.getReference(MemberThread.class, id); 
       memberThread.getId(); 
      } catch (EntityNotFoundException enfe) { 
       throw new NonexistentEntityException("The memberThread with id " + id + " no longer exists.", enfe); 
      } 
      List<String> illegalOrphanMessages = null; 
      List<Reply> replysOrphanCheck = memberThread.getReplys(); 
      for (Reply replysOrphanCheckReply : replysOrphanCheck) { 
       if (illegalOrphanMessages == null) { 
        illegalOrphanMessages = new ArrayList<String>(); 
       } 
       illegalOrphanMessages.add("This MemberThread (" + memberThread + ") cannot be destroyed since the Reply " + replysOrphanCheckReply + " in its replys field has a non-nullable memberThread field."); 
      } 
      if (illegalOrphanMessages != null) { 
       throw new IllegalOrphanException(illegalOrphanMessages); 
      } 
      SiteMember member = memberThread.getMember(); 
      if (member != null) { 
       member.getMemberThread().remove(memberThread); 
       member = em.merge(member); 
      } 
      em.remove(memberThread); 
      ut.commit(); 
     } finally { 
      if (em != null) { 
       em.close(); 
      } 
     } 
    } 

這將同時刪除SiteMember和MemberThread對象,因爲MemberThread具有SiteMember.how的外鍵可以刪除我只MemberThread?

感謝..

回答

0

分析

在你MemeberThread類,你有一個CascadeType.ALL一個SiteMember。 CascadeType說明在持久性上下文中進行更改時要調用什麼樣的級聯操作。

CascadeType API

定義組被傳播到 相關實體級聯操作。值cascade = ALL相當於 cascade = {PERSIST,MERGE,REMOVE,REFRESH,DETACH}。

調用em.remove(memberThread)將移除SiteMember上的所有操作。

解決方案

更改SiteMember您的級聯型MemberThread類:

@ManyToOne(cascade={ 
    CascadeType.PERSIST, CascadeType.MERGE, 
    CascadeType.REFRESH, CascadeType.DETACH 
}) 
@JoinColumn(nullable=false) 
private SiteMember member; 

立即刪除操作將不被級聯。

+0

它工作正常。感謝您分析答覆.. :) – bews99 2012-07-11 13:09:21

+0

你能告訴我什麼「CascadeType.DETACH」嗎?我的API沒有它,爲什麼? – bews99 2012-07-11 13:18:18

+0

它分離。 Google在JPA實體生命週期的持久化上下文中理解所有類型。你的API沒有DETACH?什麼是CascadeType的完全限定名稱? – JMelnik 2012-07-11 13:27:54