Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Data JPA Pagination (Pageable) with Dynamic Queries

I have a simple query as follows "select * from USERS". I also use Pageable to enable pagination.

This query may have optional predicates based on the given parameters being null or not.

For example if "code" parameter is given and not null, then the query becomes "select * from USERS where code = :code";

As far as I know I cannot implement this using @Query annotation. I can implement a custom repository and use EntityManager to create a dynamic query. However, I am not sure how I can integrate "Pageable" with that to get back paginated results.

How can I achieve this?

like image 647
led Avatar asked Oct 31 '13 15:10

led


People also ask

Which methods should be used for pagination with JPQL?

For all JPA query objects (except for native SQL queries), you would use pagination through the setMaxResults(int) and setFirstResult(int) methods.

How does JPA pagination works internally?

Pagination is a simple but important feature to limit the size of your result set to a number of records that can get efficiently processed by your application and the user. You can configure it with JPA and Hibernate by calling the setFirstResult and setMaxResults on the Query or TypedQuery interface.

How do I create a dynamic native query in Spring data JPA?

If you need to write dynamic queries to retrieve a single JPA entity, you would need to implement: <T> T findOne(QueryCallback<T> callback); If you need to write dynamic queries with pagination support, you would need to implement: <T> Page<T> findAll(Pageable pageable, QueryCallback<Page<T>> callback);

What is difference between PagingAndSortingRepository and JpaRepository?

PagingAndSortingRepository provides methods to do pagination and sort records. JpaRepository provides JPA related methods such as flushing the persistence context and delete records in a batch.


1 Answers

This is very easy to do in Spring Data using QueryDSL (as alternative to the criteria API). It is supported out of the box with the following method of QueryDSLPredicateExecutor where you can just pass null as the Predicate if no restrictions are to be applied:

Page<T> findAll(com.mysema.query.types.Predicate predicate,
                Pageable pageable)

Using QueryDSL may not be an option for you however if you look at the following series of tutorials you might get some ideas.

http://www.petrikainulainen.net/programming/spring-framework/spring-data-jpa-tutorial-part-nine-conclusions/

The scenario you have is actually discussed by the author in the comments to part 9 of his guide.

like image 56
Alan Hay Avatar answered Nov 06 '22 19:11

Alan Hay