【问题标题】:NHibernate criteria query using Max() projection使用 Max() 投影的 NHibernate 标准查询
【发布时间】:2014-05-12 15:11:20
【问题描述】:

我必须使用 NHibernate 实现类似的东西

DetachedCriteria maxDateQuery = DetachedCriteria.forClass(FtpStatus.class);
ProjectionList proj = Projections.projectionList();
proj.add(Projections.max("datetime"));
proj.add(Projections.groupProperty("connectionid"));
maxDateQuery.setProjection(proj);

Criteria crit = s.createCriteria(FtpStatus.class);
crit.add(Subqueries.propertiesEq(new String[] {"datetime", "connectionid"}, maxDateQuery));

List<FtpStatus> dtlList = crit.list();

(这个sn-p来自Hibernate criteria query using Max() projection on key field and group by foreign primary key

我的问题是 Nhibernate 没有实现此行中使用的“Subqueries.propertiesEq”:

crit.add(Subqueries.propertiesEq(new String[] {"datetime", "connectionid"}, maxDateQuery));

您能建议一个解决方法吗?

【问题讨论】:

    标签: c# hibernate nhibernate


    【解决方案1】:

    这里的答案是(谈论NHibernate使用EXISTS 而不是IN。查询看起来像这样

    // the below outer query, has essential feature
    // ALIAS name "outer"
    // and this is used here, in the "subquery"
    var maxDateQuery = DetachedCriteria.For<MyEntity>("myEntity")
        .SetProjection(
            Projections.ProjectionList()
            .Add(Projections.GroupProperty("MyId"))
            .Add(Projections.Max("MyDate"))
            )
            .Add(Restrictions.EqProperty(
            Projections.Max("MyDate"),
            Projections.Property("outer.MyDate")) // compare inner MAX with outer current
            )
            .Add(Restrictions.EqProperty("MyId", "outer.MyId")) // inner and outer must fit
        ;
    
    // here ... the "outer" is essential, because it is used in the subquery
    var list = session.CreateCriteria<Contact>("outer")
        .Add(Subqueries.Exists(maxDateQuery))
        ... // e.g. paging
        .List<MyEntity>();
    

    这将创建这样的查询:

    FROM [MyEntityTable] outer
    WHERE exists 
    (
      SELECT  myEntity.MyId
        , max(myEntity.MyDate) 
       FROM [MyEntityTable] myEntity
       WHERE    myEntity.MyId         = outer.MyId   // matching ID
       GROUP BY myEntity.MyId
       HAVING   max(myEntity.MyDate)  = outer.MyDate // matching max and current date
    )
    

    QueryOver 语法中的相同类型的查询(甚至更复杂)可以在这里找到:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多