要从数据库中删除某些内容,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
}