Pergunta

I am relatively new to Hibernate so I am still finding hard to understand a few concepts. And one of them is the owning.

I have a relationship between 2 objects.

Conversation

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

ConversationParticipant

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

What I want to achieve is that when someone removes the participant from the list of the participants and update object conversation this casscades and removes the ConversationParticipant entry from the db.

Is my mapping wrong for this. The code runs find, it removes everything that it is suppose to and then it updates the Conversation object, however the participants are still there after refreshing the page.

Any ideas? Suggestions

Foi útil?

Solução

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
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top