2

我对 Hibernate 比较陌生,所以我仍然很难理解一些概念。其中之一就是拥有。

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

对话

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

对话参与者

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

我想要实现的是,当有人从参与者列表中删除参与者并更新对象对话时,这会级联并从数据库中删除 ConversationParticipant 条目。

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

有任何想法吗?建议

4

1 回答 1

3

要从数据库中删除某些内容,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上设置了when 。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
}
于 2012-12-26T13:31:34.813 回答