I am using the Hibernate JPA and have an entity which contains a ManyToMany collection. I would like to be notified when changes to the collection have been changed. I tried using an EntityListener, however when an item was added to the collection, the listener's @PreUpdate/@PostUpdate methods were not called. Below is some code of the entity setup I am using.
Any suggestions on how to receive notifications on changes to the collections contained in an entity? Thanks.
Code:
@Entity
@Inheritance(strategy=InheritanceType.JOINED)
public class Group{
private String name;
@ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
private Set<Person> members = new HashSet<Person>();
public void addMember(Person person){
members.add(person);
}
public Set<Person> getMembers(){
return members;
}
public void setMembers(Set<Person> members){
this.members = members;
}
//...
}
@Entity
@EntityListeners({TeamEntityListener.class})
public class Team extends Group{
private Person coach;
//...
}
@Entity
public class Person{
private String name;
//...
}
public class TeamEntityListener{
@PostUpdate
public void postUpdate(Team team){
System.out.println("The team " + team.getName() + " has been updated");
//update code
}
}
Person john = new Person("John Doe");
entityManager.persist(john);
Team team = new Team();
team.setName("TeamName");
entityManager.persist(team);
//..
team.addMember(john);
entityManager.merge(entity); //No update notification received for the team
//..
HashSet<Person> members = new HashSet<Person>(team.getMembers());
members.add(new Person("Jane Doe"));
team.setMembers(members);
entityManager.merge(entity); //No update notification received for the team