【问题标题】:Hibernate native query is throwing exception for "ORDER BY FIELD()"Hibernate 本机查询引发“ORDER BY FIELD()”异常
【发布时间】:2020-06-29 10:14:23
【问题描述】:

我有一个 Spring Boot 项目(版本:2.0.0.M1),我正在使用 MySQL DB。

我的用户存储库扩展了JpaRepository<UserEntity, Integer>。将我的 Spring Boot 版本升级到 2.x.x.RELEASE 后,以下方法抛出异常:

@Query(value = "Select * from user as u where u.is_deleted = FALSE order by field (u.id, :idList)",
nativeQuery = true)
Page<UserEntity> findNonDeletedOrderByIdList(@Param("idList") List<Integer> idList, Pageable pageable);

例外是:

java.lang.IllegalArgumentException:无法将给定的参数名称 [idList] 解析为 QueryParameter 引用

请帮帮我。

注意:可能与Hibernate criteria for sql ORDER BY FIELD重复

更新:

我不知道为什么,在 order by 之前插入 AND u.id IN (:idList) 之后它正在工作

@Query(value = "Select * from user as u where u.is_deleted = FALSE AND u.id IN (:idList) order by field (u.id, :idList)", nativeQuery = true)
Page<UserEntity> findNonDeletedOrderByIdList(@Param("idList") List<Integer> idList, Pageable pageable);

谁能解释一下?

【问题讨论】:

  • order by 子句中不能使用参数,只能使用 where 子句。
  • 我已经提到,这段代码在以前的引导版本上运行良好。现在它在插入“IN”运算符后工作正常。 @M.Deinum
  • 因为 IN 是 where 子句的一部分,而不是 order by

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


【解决方案1】:

如果我理解你的问题,我认为你的 SQL 无效。

排序依据不能有参数

试试这个:

@Query(value = "Select * from user as u where u.is_deleted = FALSE order by u.id ASC, nativeQuery = true)
Page<UserEntity> findNonDeletedOrderByIdList(Pageable pageable);

【讨论】:

  • SQL 对 MySQL 5.6 有效。我已经提到,这段代码在以前的启动版本上运行良好。
【解决方案2】:

我不知道为什么,在order by 之前插入AND u.id IN (:idList) 之后它可以工作

@Query(value = "Select * from user as u where u.is_deleted = FALSE AND u.id IN (:idList) order by field (u.id, :idList)", nativeQuery = true)
Page<UserEntity> findNonDeletedOrderByIdList(@Param("idList") List<Integer> idList, Pageable pageable);

【讨论】:

    猜你喜欢
    • 2015-03-10
    • 2011-11-18
    • 2012-04-12
    • 1970-01-01
    • 2018-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-17
    相关资源
    最近更新 更多