I'm using JPA 2.0, Hibernate 4.1.0.Final, Spring 3.1.1.RELEASE, and Java 1.6. I have this entity with a one-to-many relationship to another entity …
import javax.persistence.CascadeType;
...
@Entity
@Table(name = "classroom")
public class Classroom implements Serializable
{
...
@OneToMany(mappedBy = "classroom", cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REMOVE})
private Set<ClassroomUser> roster;
However, when I update my entity with a different set of ClassroomUser objects
classroom.setRoster(newRoster);
and save the entity, all the previous ClassroomUser objects remain. What is the proper/shortest way to update my entity while removing all the orphan records from the database?
Thanks, - Dave
Use
orphanRemoval:Whenever an entry is removed from the persistent set, it will get deleted. And this means you need to work with the persistent set. I.e. you are not allowed to replace the set, instead you should do:
EXAMPLE how to synchronize persistent set with a user required set:
This approach might seem a little bit complex. You might be able to create something simpler (but probably not too much) with custom
equals/hashCodeand someSet<E>manipulation methods (e.g. from Guava).