小编典典

如何在hibernate状态下使用HAVING COUNT(*)

hibernate

我需要创建一个查询,并且需要COUNT(*)HAVING COUNT(*) = x

我正在解决使用CustomProjection该类的问题,该类是我在某个地方下载的。

这是我尝试实现的SQL:

select count(*) as y0_, this_.ensayo_id as y1_ from Repeticiones this_
inner join Lineas linea1_ on this_.linea_id=linea1_.id
where this_.pesoKGHA>0.0 and this_.nroRepeticion=1 and linea1_.id in (18,24)
group by this_.ensayo_id
having count(*) = 2

这是代码,我在其中使用ProjectionHibernate类:

critRepeticion.setProjection(Projections.projectionList()
                .add( Projections.groupProperty("ensayo") )
                .add( CustomProjections.groupByHaving("ensayo_id",Hibernate.LONG,"COUNT(ensayo_id) = "+String.valueOf(lineas.size()))
                .add( Projections.rowCount() )
                );

错误是:

!STACK 0
java.lang.NullPointerException
at org.hibernate.criterion.ProjectionList.toSqlString(ProjectionList.java:50)
at org.hibernate.loader.criteria.CriteriaQueryTranslator.getSelect(CriteriaQueryTranslator.java:310)
at org.hibernate.loader.criteria.CriteriaJoinWalker.<init>(CriteriaJoinWalker.java:71)
at org.hibernate.loader.criteria.CriteriaLoader.<init>(CriteriaLoader.java:67)
at org.hibernate.impl.SessionImpl.list(SessionImpl.java:1550)
at org.hibernate.impl.CriteriaImpl.list(CriteriaImpl.java:283)
at ar.com.cse.cseagro.controller.RepeticionController.buscarEnsayo(RepeticionController.java:101)

如果我用CustomProjections类注释该行,则查询工作正常,但是我没有HAVING COUNT(*)在SQL中获得过滤器…

基本上,查询会尝试在一个主详细信息架构中检索同时显示详细信息列表的所有主记录,例如,如果您想知道“哪些发票同时包含A和B产品”。

这就是为什么如果IN子句中有3个项目,则需要使用HAVING COUNT = 3子句的原因。

有什么想法或建议吗?最好的祝福,


阅读 386

收藏
2020-06-20

共1个答案

小编典典

我解决了这个问题。我将CusotmProjections类替换为:

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

其中groupBy,别名和类型为:

 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;

而魔术是在groupby String上。–

2020-06-20