HOW to use HAVING COUNT(*) with hibernate

后端 未结 4 1847
面向向阳花
面向向阳花 2020-12-10 13:58

I need to create a query and I need COUNT(*) and HAVING COUNT(*) = x.

I\'m using a work around that uses the CustomProjection

相关标签:
4条回答
  • 2020-12-10 14:26

    criteria.add(Restrictions.sqlRestriction("1=1 having count(*) = 2"));

    0 讨论(0)
  • 2020-12-10 14:28

    Here is my sample, it works fine, maybe useful :

    My sql query :

    select COLUMN1, sum(COLUMN2) from MY_TABLE group by COLUMN1 having sum(COLUMN2) > 1000;

    And Criteria would be :

     Criteria criteria = getCurrentSession().createCriteria(MyTable.Class);
      ProjectionList projectionList = Projections.projectionList();
      projectionList.add(Projections.property("column1"), "column1");
      projectionList.add(Projections.sqlGroupProjection("sum(column2)  sumColumn2 ", "COLUMN1 having sum(COLUMN2) > 1000" , new String[]{"sumColumn2"}, new org.hibernate.type.Type[]{StandardBasicTypes.STRING}));
      criteria.setProjection(projectionList);
      criteria.List();
    
    0 讨论(0)
  • 2020-12-10 14:31

    If someone needs to do it in grails it would be like:

    projections {
        groupProperty("id")
        sqlGroupProjection(...)
        rowCount()
    }
    

    Where sqlGroupProjection is available since 2.2.0

    /**
     * Adds a sql projection to the criteria
     * 
     * @param sql SQL projecting
     * @param groupBy group by clause
     * @param columnAliases List of column aliases for the projected values
     * @param types List of types for the projected values
     */
    protected void sqlGroupProjection(String sql, String groupBy, List<String> columnAliases, List<Type> types) {
        projectionList.add(Projections.sqlGroupProjection(sql, groupBy, columnAliases.toArray(new String[columnAliases.size()]), types.toArray(new Type[types.size()])));
    }
    

    http://grepcode.com/file/repo1.maven.org/maven2/org.grails/grails-hibernate/2.2.0/grails/orm/HibernateCriteriaBuilder.java/#267

    0 讨论(0)
  • 2020-12-10 14:41

    I figured out the problem. I replace CusotmProjections class, with:

    .add( Projections.sqlGroupProjection("ensayo_id", groupBy , alias, types));
    

    where groupBy, alias and types are:

     String groupBy = "ensayo_id" + " having " + "count(*) = " + String.valueOf(lineas.size());
     String[] alias = new String[1]; 
     Alias[0] = "ensayo_id"; 
     Type[] types = new Type[1]; 
     types[0] = Hibernate.INTEGER;
    

    and the magic is on groupby String. –

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