0

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.

BenMorel
  • 34,448
  • 50
  • 182
  • 322
  • 1
    Here's the relevant documentation: http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html_single/. If you open the DTD file at http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd, you'll discover that there is no role nor readonly attribute in a set. Your documentation is probably obsolete. Use the reference documentation. – JB Nizet Aug 01 '11 at 10:20

1 Answers1

0

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

Stefan Steinegger
  • 63,782
  • 15
  • 129
  • 193