【问题标题】:How configure NHibernate to map to an array if there is no index in the table?如果表中没有索引,如何配置 NHibernate 映射到数组?
【发布时间】:2009-11-17 11:43:22
【问题描述】:

我有一个现有的 POCO 类库,其中子集合都存储在数组中。例如,Customer 类有一个 Invoice[] 数组来保存其发票:

class Customer
{
    public int ID;
    public Invoice[] _invoices;
}

class Invoice
{
    public int ID;
    public int CustomerID;
    public string SomeData;
}

我无法更改这些类,我想使用 NHibernate 将它们映射到现有数据库。

我查看了<array> 映射,但它似乎需要<index> 元素。在我的数据库中,[Invoice] 表没有索引列。加载客户发票时,我不希望它们位于数组中的任何特定位置。

我有什么选择?

【问题讨论】:

    标签: nhibernate


    【解决方案1】:

    很遗憾,您的选择是更改班级或餐桌。

    A) 您可以更改Customer 以将发票声明为IList 而不是数组;然后您就可以将它们映射为unsorted bag。你甚至可以让它按某个列排序:

    <bag name="Invoices" table="Invoices" order-by="ID ASC"> <!-- order-by is optional -->
      <key column="CustomerID"/>
      <element column="SomeData" type="String"/>
      <!-- or use one-to-many if Invoice is mapped as entity -->
      <one-to-many class="Whatever.Invoice, Whatever"/>
    </bag>
    

    B)。您可以更改表格以包含索引列并将发票映射为真实的&lt;array&gt;

    <array name="Invoices" table="Invoices" order-by="ID ASC"> <!-- order-by is optional -->
      <key column="CustomerID"/>
      <index column="IndexNr"/>
      <element column="SomeData" type="String"/>
    </array>
    

    【讨论】:

    • @ChssPly76:这是一个相当大的项目,所以我愿意在不更改类或数据库的情况下投入大量时间来实现这一目标。如果我愿意扩展 NHibernate 并提供我自己的 Array 映射实现怎么办?这很简单(我对 NHibernate 完全陌生,所以我不知道其中涉及到什么)?我可以将默认数组映射子类化并仅在内存中动态生成顺序索引值吗?也许我应该在 NH 邮件列表上讨论这个...
    • 你当然可以实现你自己的集合类型;您需要实现IUserCollectionType 才能这样做,并通过映射中的collection-type 属性引用您的类名。这是一篇关于该主题的文章:javalobby.org/java/forums/m91832311.html;它处理 Hibernate / java,但几乎所有东西都应该直接移植到 NHibernate。
    • @ChssPly76:感谢您的指点。我检查了IUserCollectionTypeArrayTypePersistentArrayHolder 类。看来我可以毫不费力地继承 ArrayType
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-16
    • 1970-01-01
    • 2021-10-23
    • 2010-11-22
    • 2021-01-01
    • 1970-01-01
    相关资源
    最近更新 更多