Nhibernate one-to-many with table per subclass

时间:2010-04-09 05:16:34

标签: nhibernate subclass one-to-many n2

我正在定制N2CMS的数据库结构,并遇到了一个问题。这两个类列在下面。

public class Customer : ContentItem
{
  public IList<License> Licenses { get; set; }
}

public class License : ContentItem
{
  public Customer Customer { get; set; }
}

nhibernate映射如下。

  <class name="N2.ContentItem,N2" table="n2item">
    <cache usage="read-write" />
    <id name="ID" column="ID" type="Int32" unsaved-value="0" access="property">
      <generator class="native" />
    </id>
    <discriminator column="Type" type="String" />
  </class>

  <subclass name="My.Customer,My" extends="N2.ContentItem,N2" discriminator-value="Customer">
    <join table="Customer">
      <key column="ItemID" />
      <bag name="Licenses" generic="true" inverse="true">
        <key column="CustomerID" />
        <one-to-many class="My.License,My"/>
      </bag>
    </join>
  </subclass>

  <subclass name="My.License,My" extends="N2.ContentItem,N2" discriminator-value="License">
    <join table="License" fetch="select">
      <key column="ItemID" />
      <many-to-one name="Customer" column="CustomerID"  class="My.Customer,My" not-null="false" />
    </join>
  </subclass>

然后,当获取Customer的实例时,customer.Licenses始终为空,但实际上数据库中存在用于客户的许可证。当我检查nhibernate日志文件时,我发现SQL查询就像:

SELECT   licenses0_.CustomerID     as CustomerID1_,
         licenses0_.ID             as ID1_,
         licenses0_.ID             as ID2_0_,
         licenses0_1_.CustomerID   as CustomerID7_0_,
FROM     n2item licenses0_
         inner join License licenses0_1_
           on licenses0_.ID = licenses0_1_.ItemID
WHERE    licenses0_.CustomerID = 12 /* @p0 */

似乎nhibernate认为CustomerID在'n2item'表中。我不知道为什么,但为了使它工作,我认为SQL应该是这样的。

SELECT   licenses0_.ID             as ID1_,
         licenses0_.ID             as ID2_0_,
         licenses0_1_.CustomerID   as CustomerID7_0_,
FROM     n2item licenses0_
         inner join License licenses0_1_
           on licenses0_.ID = licenses0_1_.ItemID
WHERE    licenses0_1_.CustomerID = 12 /* @p0 */

任何人都可以指出我的映射有什么问题吗?如何获得一个客户的正确许可?提前谢谢。

1 个答案:

答案 0 :(得分:0)

我不确定SQL是否不正确,因为父类映射使用了一个鉴别器,所以我希望所有属性都存储在与基类(n2item)相同的表中。但是我不熟悉“连接表”语法,我通常使用join-subclass,所以我可能会误解。

假设子类映射是正确的,许可证的问题可能与没有为该集合设置Cascade设置有关吗?