I'm taking the following many-to-many mapping example from this Hibernate Mapping Cheat Sheet:
<class name="Foo" table="foo">
...
<set role="bars" table="foo_bar">
<key column="foo_id"/>
<many-to-many column="bar_id" class="Bar"/>
</set>
</class>
<class name="Bar" table="bar">
...
<set role="foos" table="foo_bar" readonly="true">
<key column="bar_id"/>
<many-to-many column="foo_id" class="Foo"/>
</set>
</class>
A Foo has several bars
, and a Bar has several foos
.
Because Bar.foos is declared readonly, I guess that I just need this simple method:
public class Foo {
public void addBar(Bar bar) {
this.bars.add(bar);
}
}
And not:
public class Foo {
public void addBar(Bar bar) {
this.bars.add(bar);
bar.foos.add(foo); // readonly
}
}
My guess is that I cannot ensure consistency that way (adding back the Foo
to the Bar
). Does Hibernate guarantee this consistency itself, by automatically updating Bar.foos
whenever I add a Foo.bars
, or is the Bar.foos
collection static once initialized?
For example if I do this:
Foo foo = new Foo();
Bar bar = new Bar();
bar.getFoos().size(); // expected to return 0
foo.addBar(bar);
bar.getFoos().size(); // expected to return 1
Will the return values of size()
be the ones I expect?
I could not find the relevant documentation yet, so a pointer would be very helpful.
One of the references should be marked inverse="true"
, not readonly.
The inverse part is not stored by NH. But, of course, you get consistency problems in memory when you work with that objects.
Take a look at the reference documentation, Bidirectional associations with join tables, Many-to-many