Hibernate: How to get only result objects whose count value are greater than a threshold

StackOverflow https://stackoverflow.com/questions/22226932

  •  10-06-2023
  •  | 
  •  

Question

This is my query_string. It delivers all persons including count(persAccsBOs). This string works.

hql_query_string = ""
+ "select distinct pers, count(persAccsBOs) as anzBo from Person as pers"
+ " inner join pers.personenAttribute as persAttr inner join persAttr.pa_pk.attribut as pAttr"
+ " inner join pers.accounts as persAccs"
+ " inner join persAccs.berechtigungsobjekte as persAccsBOs"
+ " where pAttr.name= :attrName"
+ " and persAttr.wert= :attrValue"
+ " group by pers";

Now i want to get only persons whose count(persAccsBOs) is greater than a threshold. This doesnt work:

hql_query_string = ""
+ "select distinct pers, count(persAccsBOs) as anzBo from Person as pers"
+ " inner join pers.personenAttribute as persAttr inner join persAttr.pa_pk.attribut as pAttr"
+ " inner join pers.accounts as persAccs"
+ " inner join persAccs.berechtigungsobjekte as persAccsBOs"
+ " where pAttr.name= :attrName"
+ " and persAttr.wert= :attrValue"
+ " and count(persAccsBOs) >=  :threshold"
+ " group by pers";

I get the error message:

14:55:27.121 [main] DEBUG org.hibernate.engine.jdbc.spi.SqlExceptionHelper 139 logExceptions - could not extract ResultSet [n/a] java.sql.SQLException: Invalid use of group function

Can you help me with that?

Was it helpful?

Solution

Alexander,

I believe this will work:

hql_query_string = ""
+ "select distinct pers, count(persAccsBOs) as anzBo from Person as pers"
+ " inner join pers.personenAttribute as persAttr inner join persAttr.pa_pk.attribut as pAttr"
+ " inner join pers.accounts as persAccs"
+ " inner join persAccs.berechtigungsobjekte as persAccsBOs"
+ " where pAttr.name= :attrName"
+ " and persAttr.wert= :attrValue"
+ " group by pers"
+ " having count(persAccsBOs) >=  :threshold";

Conditions on aggregated fields must be made with the having clause, not inside the where clause.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top