To delete something from the database, delete()
must be called:
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
}
An exception to this rule is when orphanRemoval = true
is set on the OneToMany
association. In this case, removing the participant from the collection of participants will remove it from the database:
@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
}