I have two simple entities: Person and Organization. They have a ManyToMany association. My Person Class looks like
Code:
@Entity
@Table(name = "person")
public class Person {
long id;
String firstName;
String lastName;
int age;
String email;
Collection<Organization> organizations;
@ManyToMany(targetEntity = Organization.class,
cascade = { CascadeType.ALL })
@Cascade({org.hibernate.annotations.CascadeType.ALL})
@JoinTable(name = "person_to_org",
joinColumns = @JoinColumn(name = "pid"),
inverseJoinColumns = @JoinColumn(name = "oid"))
public Collection<Organization> getOrganizations() {
return organizations;
}
public void setOrganizations(Collection<Organization> organizations) {
this.organizations = organizations;
}
...
}
and my Organization class looks like
Code:
@Entity
@Table(name = "organization")
public class Organization {
long id;
String name;
Collection<Person> members;
@ManyToMany(targetEntity = Person.class,
cascade = { CascadeType.ALL },
mappedBy = "organizations")
@Cascade({org.hibernate.annotations.CascadeType.ALL})
public Collection<Person> getMembers() {
return members;
}
public void setMembers(Collection<Person> members) {
this.members = members;
}
...
}
Now I have a simple function in my Service class, which looks like:
Code:
@Transactional(propagation=Propagation.REQUIRES_NEW, readOnly=false)
public void add2Org(List<Person> persons, Organization org) {
List<Person> members = getMembers(org);
members.addAll(persons);
org.setMembers(members);
orgDao.update(org);
}
orgDao.update() simply calls the update function of a session. Then I wrote a test case in which simply adds 6 ppl to the organization Good Company:
Code:
List<Organization> orgs = service.getAllOrgs();
List<Person> persons = service.getAllPersons();
// put in a map so I can find a org easily
Map<String, Organization> orgMap = new HashMap<String, Organization> ();
for (Organization o : orgs) {
orgMap.put(o.getName(), o);
}
// get 6 ppl from top of the list
List<Person> somePpl = persons.subList(0, 6);
service.add2Org(somePpl, orgMap.get("Good Company"));
Problem: the join table failed to get updated! Hibernate only updates that Good Company instance and those 6 ppl (which don't really have any change) but forgets to update my join table.
Can anyone please throw me some ideas? I have been looking for an answer for quite a while.
Thanks.
Need help with Hibernate? Read this first:
http://www.hibernate.org/ForumMailingli ... AskForHelpHibernate version: Mapping documents:Code between sessionFactory.openSession() and session.close():Full stack trace of any exception that occurs:Name and version of the database you are using:The generated SQL (show_sql=true):Debug level Hibernate log excerpt:Problems with Session and transaction handling?
Read this:
http://hibernate.org/42.htmlCode: