【问题标题】:Need to convert a subquery that selects multiple values to an nhibernate query (criteria or hql)需要将选择多个值的子查询转换为 nhibernate 查询(条件或 hql)
【发布时间】:2012-06-30 07:26:48
【问题描述】:

我有以下查询需要转换为 nhibernate:

SELECT  o.* 
FROM orders o
INNER JOIN 
(
        -- get the most recent orders based on end_date (this implies the same order can exist in the orders table more than once)
        SELECT o2.order_id, MAX(o2.end_date) AS max_end_date 
        FROM orders o2
        GROUP BY o2.order_id
) most_recent_orders 
                ON o.order_id=most_recent_orders.order_id
                AND o.end_date=most_recent_orders.max_end_date
-- of the most recent orders, get the ones that are complete                
WHERE o.is_complete=1

我知道 hql 不支持加入子查询,这就是为什么这不起作用。我不能使用“in”语句,因为子查询选择了 2 个值。我尝试使用休眠文档中的建议:

http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/queryhql.html#queryhql-tuple

from Cat as cat
where not ( cat.name, cat.color ) in (
    select cat.name, cat.color from DomesticCat cat
)

但这引发了错误,因为 Sql Server 不喜欢“in”语句中的多个值。

任何帮助将不胜感激!我愿意接受使用 Criteria 或 Hql 的解决方案。

【问题讨论】:

    标签: nhibernate subquery hql criteria


    【解决方案1】:

    这是使用子查询来实现相同的

    var maxDateQuery = DetachedCriteria.For<Order>()
        .Add(Restrictions.PropertyEq("OrderId", "order.OrderId"))
        .SetProjection(Projections.Property("EndDate"));
    
    var results = session.CreateCriteria<Order>("order")
        .Add(Subqueries.Eq("EndDate",maxDateQuery))
        .Add(Restrictions.Eq("IsComplete", true))
        .List<Order>();
    

    【讨论】:

    • “order.OrderId”从何而来?我在查询中的任何地方都没有看到名为“order”的别名?
    • 现在它会抛出一个异常,因为它将“order.OrderId”视为字符串文字而不是对其进行插值。错误:NHibernate.QueryException:NHibernate.Criterion.SimpleExpression 中的类型不匹配:Id 预期类型 System.Guid,实际类型 System.String
    猜你喜欢
    • 2011-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-07
    相关资源
    最近更新 更多