HOW to use HAVING COUNT(*) with hibernate

那年仲夏 提交于 2019-11-28 11:09:07
Nicolas400

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. –

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

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();

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!