JPA2 Criteria API creates invalid SQL when using groupBy
Posted
by
Stephan
on Stack Overflow
See other posts from Stack Overflow
or by Stephan
Published on 2012-09-13T09:36:43Z
Indexed on
2012/09/13
9:37 UTC
Read the original article
Hit count: 334
JPA2 with the Criteria API seems to generate invalid SQL for PostgreSQL. For this code:
Root<DBObjectAccessCounter> from = query.from(DBObjectAccessCounter.class);
Path<DBObject> object = from.get(DBObjectAccessCounter_.object);
Expression<Long> sum = builder.sumAsLong(from.get(DBObjectAccessCounter_.count));
query.multiselect(object, sum).groupBy(object);
I get the following exception:
ERROR: column "dbobject1_.id" must appear in the GROUP BY
clause or be used in an aggregate function
The generated SQL is:
select dbobjectac0_.object_id as col_0_0_,
sum(dbobjectac0_.count) as col_1_0_, dbobject1_.id as id1001_,
dbobject1_.name as name1013_,
dbobject1_.lastChanged as lastChan2_1013_,
dbobject1_.type_id as type3_1013_
from DBObjectAccessCounter dbobjectac0_
inner join DBObject dbobject1_
on dbobjectac0_.object_id=dbobject1_.id
group by dbobjectac0_.object_id
Obviously, the first item of the select statement (dbobjectac0_.object_id) does not match the group by clause.
Simplified example
It does not even work for this simple example:
Root<DBObjectAccessCounter> from = query.from(DBObjectAccessCounter.class);
Path<DBObject> object = from.get(DBObjectAccessCounter_.object);
query.select(object).groupBy(object);
which returns
select dbobject1_.id as id924_, dbobject1_.name as name933_,
dbobject1_.lastChanged as lastChan2_933_,
dbobject1_.type_id as type3_933_
from DBObjectAccessCounter dbobjectac0_
inner join DBObject dbobject1_
on dbobjectac0_.object_id=dbobject1_.id
group by dbobjectac0_.object_id
Does anyone know how to fix this?
© Stack Overflow or respective owner