Hi!
I'm currently switching between the book "Hibernate - A Developers Notebook" and the "Hibernate Reference Documentation" to solve my understanding problem with inverse="true"....
The book and the documentation says that i have to make one side "inverse" in a association mapping and that it is regardless of which side of (e. g. a many-to-many) association it is.
I have a little testing example that consists of "Groups" and "Persons". A Group can have many Persons in it and one Person can be part of many Groups (many-to-many). I made the Group-side of the many-to-many as "inverse":
Person mapping:
Code:
<set name="groups" table="PERSON_GROUP">
<key column="PERSON_ID" />
<many-to-many class="foo.Group" column="GROUP_ID" />
</set>
Group mapping:
Code:
<set name="persons" table="PERSON_GROUP" inverse="true">
<key column="GROUP_ID" />
<many-to-many class="foo.Person" column="PERSON_ID" />
</set>
Now I generated my java-files with the "hbm2java"-task from hibernate tools, which works great.
With the following code i inserted a new group, a new person, and a association:
Code:
Person aPerson = new Person("Stefan", "Hofmann", "Bamberg");
Group aGroup = new Group("great group");
aPerson.getGroups().add(aGroup);
This works.
The following code doesn't work (ony third line changed):
Code:
Person aPerson = new Person("Stefan", "Hofmann", "Bamberg");
Group aGroup = new Group("great group");
aGroup.getPersons().add(aPerson);
Here the association isn't saved. I know this is because the inverse="true" deactivates this association somehow.
First question: why do i have to set one side as inverse="true" when the association works only in one direction then? the documentation says, that hiberate does not have enough information to build correct sql statements..... ok, i can live with it, because the documentation gives a solution:
adding two methods like this (in Person class):
Code:
public void addGroup(Group group) {
this.getGroups().add(group);
group.getPersons().add(this);
}
public void removeGroup(Group group) {
this.getGroups().remove(group);
group.getPersons().remove(this);
}
But i cannot add this methods in the class-sources because my java-files were generated by hbm2java. Ok, i could (!) change it, but after the next hbm2java-generation the changes are gone.....
Question 2: how can I use the bi-directional mapping from both sides without setting the association in my code always two times....
thanks for reading (and answering :).
Stefan.