Hibernate Criteria API - HAVING clause work arounds

前端 未结 3 640
温柔的废话
温柔的废话 2020-12-10 14:25

I\'ve written a query using Hibernate Criteria API to grab a summation of a particular value, now I need to be able to restrict the result to rows where that sum is greater

相关标签:
3条回答
  • 2020-12-10 14:52

    HHH-1700 was marked as a duplicate of HHH-1043, and therefore won't be fixed. You'll find my solution and workaround, as well as other peoples', on HHH-1043.

    0 讨论(0)
  • 2020-12-10 15:00

    http://opensource.atlassian.com/projects/hibernate/browse/HHH-1700

    0 讨论(0)
  • 2020-12-10 15:10

    I don't know of a way for Hibernate/NHibernate to use a subquery in the FROM clause but you can use them in the WHERE clause. Apologies for any Java/Hibernate code mistakes, I am more familiar with C#/NHibernate.

    
    DetachedCriteria subQuery = DetachedCriteria.forClass(Transaction.class);
    subQuery.setProjection(Projections.sum("amount"));
    subQuery.add(Expression.eqProperty("userPk", "tOuter.userPk"));
    
    DetachedCriteria outerQuery = DetachedCriteria.forClass(Transaction.class, "tOuter");
    outerQuery.setProjection(Projections.projectionList()
        .Add(Projections.sum("amount").as("sumAmount"))
        .Add(Projections.groupProperty("userPk").as("user_pk"));
    outerQuery.add(Subqueries.le(50, subQuery));
    
    
    

    This code should result in SQL similar to:

    
    SELECT tOuter.userPk as user_pk, sum(tOuter.amount) as sumAmount
    FROM transaction tOuter
    WHERE 50 <= (SELECT sum(amount) FROM transaction WHERE userPk = tOuter.userPk)
    GROUP BY tOuter.userPk
    
    

    The disadvantage of this approach is that it calculates each of the sums twice, this might have a detrimental effect on performance depending on the amount of data involved - in which case you will want to use an HQL query which does support the HAVING clause.

    0 讨论(0)
提交回复
热议问题