JPA 和 SQL 服务器的 ORDER BY 子句中的列无效

Column is invalid in the ORDER BY clause with JPA and SQL Server

当我搜索这个错误时,发现了很多结果,但所有的答案都是在数据库(SQL 服务器)级别。但是,我在使用 JPA 查询(带有 order 子句的简单计数查询)和 SQL 服务器数据库时遇到此错误。此代码适用于 MySQL 数据库。

代码:

FilterBuilder builder = new FilterBuilder("FROM RuleChangeLog A  ");
{
  builder.startWhere();
  builder.checkAndAdd1(filters[0], "and A.action LIKE ?", filters[0] );
  builder.checkAndAdd1(filters[1], "and A.ruleName like ?", filters[1] );
  builder.checkAndAdd1(filters[2], "and A.updatedBy like ?", filters[2] );
}
TypedQuery<Long> countQuery = em.createQuery("select count(A) " + builder.getJPQL(), Long.class);
        builder.setParameters(countQuery);

当我使用 运行 countQuery.getSingleResult() 方法时出现以下错误。

Caused by: com.microsoft.sqlserver.jdbc.SQLServerException: Column "rule_change_log.update_time" is invalid in the ORDER BY clause because it is not contained in either an aggregate function or the GROUP BY clause.

下面是转换后的数据库查询:

select count(rulechange0_.id) as col_0_0_ from rule_change_log rulechange0_ where 1=1 order by rulechange0_.update_time DESC

正如@Dale K 所建议的,删除查询中的 order 子句后,它起作用了。