Hibernate只读集合映射

时间:2011-08-01 09:53:06

标签: hibernate orm collections hibernate-mapping readonly-collection

我正在使用以下多对多映射示例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>

Foo有几个bars,而一个Bar有几个foos。 因为Bar.foos被声明为 readonly ,我想我只需要这个简单的方法:

public class Foo {
    public void addBar(Bar bar) {
        this.bars.add(bar);
    }
}

public class Foo {
    public void addBar(Bar bar) {
        this.bars.add(bar);
        bar.foos.add(foo); // readonly
    }
}

我的猜测是我无法确保这种方式的一致性(将Foo添加回Bar)。 Hibernate本身是否保证这种一致性,每当我添加Bar.foos时自动更新Foo.bars,或者Bar.foos集合在初始化后是静态的吗?

例如,如果我这样做:

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

size()的返回值是否符合预期?

我还没找到相关的文档,所以指针会非常有用。

1 个答案:

答案 0 :(得分:0)

其中一个引用应标记为inverse="true",而不是只读。

反向部分不由NH存储。但是,当然,当您使用这些对象时,会在内存中出现一致性问题。

查看参考文档Bidirectional associations with join tables, Many-to-many

相关问题