【问题标题】:Hibernate readonly collection mappingHibernate 只读集合映射
【发布时间】:2011-08-01 09:53:05
【问题描述】:

我正在从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 是否通过在我添加 Foo.bars 时自动更新 Bar.foos 本身来保证这种一致性,或者 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() 的返回值会是我所期望的吗?

我还没有找到相关的文档,所以一个指针会很有帮助。

【问题讨论】:

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


【解决方案1】:

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

NH 不存储逆部分。但是,当然,当您使用这些对象时,您会在内存中遇到一致性问题。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-30
    • 1970-01-01
    • 2016-08-01
    • 2011-03-17
    相关资源
    最近更新 更多