且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

何时在 NHibernate/Hibernate OneToMany 关系上使用 inverse=false?

更新时间:2023-09-04 16:07:40

正如 Matthieu 所说,您不想设置 inverse = true 的唯一情况是孩子负责更新没有意义本身,例如在孩子不知道其父母的情况下.

As Matthieu says, the only case where you wouldn't want to set inverse = true is where it does not make sense for the child to be responsible for updating itself, such as in the case where the child has no knowledge of its parent.

让我们尝试一个真实的世界,而不是人为的例子:

Lets try a real world, and not at all contrived example:

<class name="SpyMaster" table="SpyMaster" lazy="true">
  <id name="Id">
    <generator class="identity"/>
  </id>
  <property name="Name"/>
  <set name="Spies" table="Spy" cascade="save-update">
    <key column="SpyMasterId"/>
    <one-to-many class="Spy"/>
  </set>
</class>

<class name="Spy" table="Spy" lazy="true">
  <id name="Id">
    <generator class="identity"/>
  </id>
  <property name="Name"/>
</class>

间谍大师可以有间谍,但间谍永远不知道他们的间谍大师是谁,因为我们没有在间谍类中包含多对一的关系.此外(方便地)间谍可能会变成流氓,因此不需要与间谍大师相关联.我们可以按如下方式创建实体:

Spymasters can have spies, but spies never know who their spymaster is, because we have not included the many-to-one relationship in the spy class. Also (conveniently) a spy may turn rogue and so does not need to be associated with a spymaster. We can create entities as follows:

var sm = new SpyMaster
{
    Name = "Head of Operation Treadstone"
};
sm.Spies.Add(new Spy
{
    Name = "Bourne",
    //SpyMaster = sm // Can't do this
});
session.Save(sm);

在这种情况下,您会将 FK 列设置为可空,因为保存 sm 的行为会插入到 SpyMaster 表和 Spy 表中,只有在此之后它才会更新 Spy 表以设置 FK.在这种情况下,如果我们设置 inverse = true,FK 将永远不会更新.

In such a case you would set the FK column to be nullable because the act of saving sm would insert into the SpyMaster table and the Spy table, and only after that would it then update the Spy table to set the FK. In this case, if we were to set inverse = true, the FK would never get updated.