带有 Criteria API 的 JPA2 似乎为 PostgreSQL 生成了无效的 SQL。对于此代码:
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);
我得到以下异常:
ERROR: column "dbobject1_.id" must appear in the GROUP BY
clause or be used in an aggregate function
生成的 SQL 为:
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
显然,select 语句的第一项(dbobjectac0_.object_id)与group by 子句不匹配。
简化示例
它甚至不适用于这个简单的示例:
Root<DBObjectAccessCounter> from = query.from(DBObjectAccessCounter.class);
Path<DBObject> object = from.get(DBObjectAccessCounter_.object);
query.select(object).groupBy(object);
返回
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
并产生与上述相同的错误。
按 ID 而非类型分组
按照错误消息的建议按 ID 分组
Root<DBObjectAccessCounter> from = query.from(DBObjectAccessCounter.class);
Path<DBObject> object = from.get(DBObjectAccessCounter_.object);
Path<Long> objectId = from.get(DBObjectAccessCounter_.object).get(DBObject_.id);
query.select(object).groupBy(objectId);
也会导致同样的错误。
有谁知道如何解决这一问题?