【问题标题】:Nhibernate/Hibernate, lookup tables and object designNhibernate/Hibernate、查找表和对象设计
【发布时间】:2011-01-28 03:24:46
【问题描述】:

我有两张桌子。带有 CustomerID、InvoiceDate、Value、InvoiceTypeID 列的发票(CustomerID 和 InvoiceDate 组成一个复合键)和带有 InvoiceTypeID 和 InvoiceTypeName 列的 InvoiceType。

我知道我可以创建我的对象,例如:

public class Invoice
{
    public virtual int CustomerID { get; set; }
    public virtual DateTime InvoiceDate { get; set; }
    public virtual decimal Value { get; set; }
    public virtual InvoiceType InvoiceType { get; set; }
}

public class InvoiceType
{
    public virtual InvoiceTypeID { get; set; }
    public virtual InvoiceTypeName { get; set; }
}

所以生成的 sql 看起来像这样:

SELECT CustomerID, InvoiceDate, Value, InvoiceTypeID FROM Invoice WHERE CustomerID = x AND InvoiceDate = y
SELECT InvoiceTypeID, InvoiceTypeName FROM InvoiceType WHERE InvoiceTypeID = z

但我宁愿有一个执行两个选择查询来检索数据。我还想避免将子对象用于简单的查找列表。所以我的对象看起来像:

public class Invoice
{
    public virtual int CustomerID { get; set; }
    public virtual DateTime InvoiceDate { get; set; }
    public virtual decimal Value { get; set; }
    public virtual InvoiceTypeID { get; set; }
    public virtual InvoiceTypeName { get; set; }
}

我的 sql 看起来像:

SELECT CustomerID, InvoiceDate, Value, InvoiceTypeID 
FROM Invoice INNER JOIN InvoiceType ON Invoice.InvoiceTypeID = InvoiceType.InvoiceTypeID
WHERE CustomerID = x AND InvoiceDate = y

我的问题是如何为此创建映射?

我尝试过使用 join,但这尝试使用 CustomerID 和 InvoiceDate 加入,我是否遗漏了一些明显的东西?

谢谢

【问题讨论】:

    标签: nhibernate hibernate fluent-nhibernate nhibernate-mapping object-object-mapping


    【解决方案1】:

    如果您的目标是(如您所说)避免两次查询,则可以使用单个 HQL 语句检索数据:

    select i, it from Invoice i fetch join i.type it where ...
    

    ...如休眠docs 中所述。这应该只执行一个 SQL select 语句并检索所有内容,而不需要任何映射更改。

    这是一个常规的 HQL 查询,执行如下:

    IQuery q = s.CreateQuery("select i, it from Invoice i fetch join i.type it where ...");
    IList invoices = q.List();
    

    有关休眠查询语言page 的更多信息。

    【讨论】:

    • 感谢您的回答,但您实际上是如何做到的?您在哪里指定此 HQL?在映射?在代码中?我仍然不明白如何将查找表添加到映射中。谢谢。
    • 我已经用附加代码更新了我的答案,以便更好地解释它。当您需要发票数据时,您可以在您的 OO 代码中执行这样的查询,是的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-10-15
    • 2013-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-02
    相关资源
    最近更新 更多