【问题标题】:Spring JPA group by query pageable injects unnecessary ID causes syntax errorSpring JPA group by query pageable 注入不必要的 ID 导致语法错误
【发布时间】:2020-11-09 15:56:45
【问题描述】:

我正在尝试将 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);

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

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

编辑:

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

【问题讨论】:

  • 您能告诉我们您使用的是哪个春季版本吗?我试过这个查询,效果很好。
  • @Shawrup 我正在使用 Spring boot 2.1.7
  • 您是如何创建 Pageable 对象的?您可能在 pageable 中添加了排序。

标签: java spring spring-boot hibernate spring-data-jpa


【解决方案1】:

如果您不添加任何可能是您所看到的排序,则默认情况下,AFAIK Spring Data 会按表达式顺序添加实体 ID。这是有道理的,因为您需要一致的顺序,否则分页将不起作用。您必须添加排序 alertId 和 userId 才能让 MySQL 满意并获得一致的结果。

【讨论】:

    猜你喜欢
    • 2015-02-27
    • 1970-01-01
    • 2013-08-22
    • 2020-02-22
    • 2013-04-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多