从非拥有方删除实体

时间:2012-12-26 13:07:22

标签: hibernate mapping one-to-many cascade cascading-deletes

我对Hibernate比较新,所以我仍然很难理解一些概念。其中一个是拥有者。

我有两个对象之间的关系。

会话

@OneToMany(mappedBy = "conversation", cascade = CascadeType.ALL)
private List<ConversationParticipant> participants;

ConversationParticipant

@ManyToOne
@JoinColumn(name = "ConversationID")
private Conversation conversation;

我想要实现的是,当有人从参与者列表中删除参与者并更新对象会话时,这会进行casscades并从db中删除ConversationParticipant条目。

我的映射是否错误。代码运行find,它会删除它所设想的所有内容,然后它会更新Conversation对象,但是刷新页面后参与者仍然在那里。

有什么想法吗?建议

1 个答案:

答案 0 :(得分:2)

要从数据库中删除某些内容,必须调用delete()

Conversation c = session.get(Conversation.class, conversationId);
for (Iterator<ConversationParticipant> it = c.getParticipants().iterator(); it.hasNext(); ) {
    Participant p = it.next();
    it.remove(); // Hibernate doesn't care: you've removed an element from a collection
                 // which is not the owner side

    p.setConversation(null); // Hibernate will set the foreign key in the participant 
                             // to NULL, since you modified the owning side

    session.delete(p); // Hibernate will remove the row from the participant table
}

此规则的例外情况是在orphanRemoval = true关联上设置OneToMany时。在这种情况下,从参与者集合中删除参与者将从数据库中删除它:

@OneToMany(mappedBy = "conversation", cascade = CascadeType.ALL, orphanRemoval = true)
private List<ConversationParticipant> participants;

...

Conversation c = session.get(Conversation.class, conversationId);
for (Iterator<ConversationParticipant> it = c.getParticipants().iterator(); it.hasNext(); ) {
    Participant p = it.next();
    it.remove(); // Hibernate will remove the participant from the database,
                 // because orphanRemoval is set to true
}