I had the following relationship in a UserAnswer, the answer(s) a user can give to a question in a survey:
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
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:
Post a Comment