Spring JPA组通过可分页查询注入不必要的ID导致语法错误



我正在尝试将Spring Data Pageable与JPA Query(非本机(一起使用,这会导致以下异常:

Caused by: java.sql.SQLSyntaxErrorException: Expression #1 of ORDER BY clause is not in GROUP BY clause and contains nonaggregated column 'alerting.alerthisto0_.id' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by

这是我的问题:

@Query(value =
"SELECT history.alertId AS alertId, history.userId AS userId, alert.organization.id AS organizationId,"
+ " alert.status AS status, alert.createdAt AS createdAt, COUNT(history.alertId) AS alertsCount"
+ " FROM AlertHistory AS history LEFT JOIN Alert AS alert ON history.alertId=alert.id"
+ " GROUP BY history.alertId, history.userId")
Page<AlertAggregationDetails> groupByAlertIdAndUserId(Pageable pageable);

显然,因为我使用的是Pageablehistory.id,所以注入了它,这是不必要的,并导致了语法问题。如果我将history.id添加到group by部分,语法将是正确的,但显然,结果与我想要的相去甚远。我想知道是否有办法解决语法问题并继续使用Pageable。

此外,如果我删除Pageable,这个查询就可以工作,并且没有问题。

编辑:

调试完查询后,我注意到当我使用Pageable时,Spring JPA会自动将ORDER BY history.id添加到我的查询中。作为一种变通方法,我可以替换sql_mode,但我不明白为什么我不能用Pageable覆盖ORDER BY

AFAIK Spring Data默认情况下,如果您没有添加任何排序,则会按表达式的顺序添加实体id。这是有道理的,因为您想要一个一致的排序,否则分页就不起作用。您必须为MySQL添加排序alertIduserId才能获得满意的结果,并获得一致的结果。

最新更新