[英]How can I run a runtime generated query with Pageable in Spring Data?
I have a runtime generated JPQL as a String, and a PageAble object. 我有一个运行时生成的JPQL作为一个字符串和一个PageAble对象。 I want to run the JPQL query with Pageable.
我想使用Pageable运行JPQL查询。 How can I do that?
我怎样才能做到这一点?
Eg: I want a solution like this with runtime generated Query string. 例如:我想要这样的解决方案,其中包含运行时生成的查询字符串。
@Query("select u from User u")
Page<User> findUsers(Pageable pageable);
Attempt 1
尝试1
To use a query generated at runtime, the repository method will have to be declared as 要使用运行时生成的查询,必须将存储库方法声明为
@Query("?1") Page<User>
findUsers(String query, Pageable pageable)
However, @Query
is parsed at the time of initializing the application context, so this approach will fail because ?1
on its own is not a valid JPQL expression. 但是,
@Query
是在初始化应用程序上下文时解析的,因此该方法将失败,因为?1
本身不是有效的JPQL表达式。
Attempt 2
尝试2
If you use 如果您使用
@Query("?1", nativeQuery = true)
the context will initialize and you will be able to pass the generated query to the method, but the Pageable
parameter will be ignored because the query passed as the method parameter is used as-is. 上下文将初始化,您将能够将生成的查询传递给方法,但是
Pageable
参数将被忽略,因为按原样使用作为方法参数传递的查询。
So, in short, no, what you are looking for cannot be done with a Pageable
. 因此,总之,不,您要查找的内容无法通过
Pageable
完成。
Attempt 3
尝试3
If you must generate the query at runtime, you must perform the pagination yourself as well. 如果必须在运行时生成查询,则还必须自己执行分页。 An example query with MySQL as the underlying database:
使用MySQL作为基础数据库的示例查询:
@Query("select u from user u order by last_name, first_name offset (?1 - 1) * ?2 limit ?2", nativeQuery = true)
Page<User> findUsers(int page, int pageSize);
Do note that offset
and limit
are specific to MySQL and Postgres. 请注意,
offset
和limit
特定于MySQL和Postgres。 There may be a different syntax for other database products. 其他数据库产品可能有不同的语法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.