Monday, May 14, 2012

No Cascade Delete on a Collection Relationship

I had the following relationship in a UserAnswer, the answer(s) a user can give to a question in a survey:

     public SortedSet getSelectedAnswers()

I wanted to propagate all persistence operations to the collection except DELETE. I didn't want an Answer to be deleted when all UserAnswers were removed.
This is how it worked for me: 

    @ManyToMany(targetEntity=Answer.class, cascade={CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH})
    @Cascade(org.hibernate.annotations.CascadeType.SAVE_UPDATE)
    @JoinTable(name="userAnswer_answers",
            joinColumns=@JoinColumn(name="userAnswer_fk"),
            inverseJoinColumns=@JoinColumn(name="answer_fk"))
    @Sort(type = SortType.COMPARATOR, comparator = AnswerPositionComparator.class)
    public SortedSet getSelectedAnswers() {
       
        return selectedAnswers;
    }


If you don't use CascadeType.ALL, Hibernate doesn't cascade the save of an entity's Collection properties when using the PERSIST annotation. You have to explicitly use the org.hibernate.annotations.CascadeType.SAVE_UPDATE annotation.

Source here.

No comments: