简体   繁体   中英

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. I want to run the JPQL query with Pageable. 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

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.

Attempt 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.

So, in short, no, what you are looking for cannot be done with a Pageable .


Attempt 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:

@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. There may be a different syntax for other database products.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM