对hibernate进行SQL查询

本文关键字:查询 SQL 进行 hibernate | 更新日期: 2023-09-27 18:07:55

我如何得到这个SQL查询Nhibernate?

SELECT Customer.name
FROM Company INNER JOIN Customer ON Company.CompanyId = Customer.CompanyId
where CompanyId = 2

对hibernate进行SQL查询

如果你熟悉LINQ它是非常非常简单的,
必须像实体一样直接访问引用文件。你会得到那个实体的属性,等等直到第n个节点

Nhibernate会把引用字段当作实体处理。

        //Here is the sample this may work 
        //CustomerList is a nhibernate entity list.
        //CompanyId is also an entity which is a reference to the CompanyId of Company table.
        // you will get the list of customers based on condition. 
        var CustomerList = new List<Customer>();
        var custList = from cust in CustomerList where cust.CompanyId.CompanyId == 2 select cust;

假设您有一个代表ID为2的公司的公司。您可以使用iccriteria:

return this.GetSession().CreateCriteria<Customer>()
    .Add(Restrictions.Eq("Company", company))
    .List<Customer>();

这将返回与公司关联的客户列表(假设客户类上的属性称为"company")。

要获取名称,只需执行:

customers.Select(c => c.name);

我建议使用这种方法,因为您知道所有客户将在一个db命中加载,而不是一次加载一个。