Nhibernate / Hibernate,查找表和对象设计

时间:2010-03-16 14:15:28

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

我有两张桌子。包含CustomerID,InvoiceDate,Value,InvoiceTypeID(CustomerID和InvoiceDate组成复合键)和InvoiceType与InvoiceTypeID和InvoiceTypeName列的发票。

我知道我可以创建我的对象:

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加入,我错过了一些明显的东西吗?

由于

1 个答案:

答案 0 :(得分:1)

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

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

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

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

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

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