0

这是我的代码,

SiteMember 类

@OneToMany(mappedBy = "member",cascade=CascadeType.ALL)
    private List<MemberThread> memberThread = new ArrayList<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 的外键。我怎样才能只删除 MemberThread?

谢谢..

4

1 回答 1

0

分析

在您的 MemeberThread 类中,您有一个带有 CascadeType.ALL 的 SiteMember。CascadeType 告诉在持久上下文中进行更改时要调用哪种级联操作。

来自CascadeType API

定义传播到关联实体的可级联操作集。值 cascade=ALL 等价于 cascade={PERSIST, MERGE, REMOVE, REFRESH, DETACH}。

调用 em.remove(memberThread) 将通过删除它来级联 SiteMember 上的所有操作。

解决方案

在 MemberThread 类中更改 SiteMember 的级联类型

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

现在 REMOVE 操作将不会级联。

于 2012-07-11T12:27:06.440 回答