Skip to content
Advertisement

How to paginate a JPA Query

I have a submission table with columns like ID, Name, Code among other properties. My requirement is to search for records based on the mentioned properties and return a paginated set.

This is the pseudocode for what I am looking for:

JavaScript

There seem to be many options like CriteriaBuilder, NamedQuery, etc. Which is the most efficient one in this situation?

Advertisement

Answer

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

JavaScript

JPA will perform the pagination for you.

Named queries are just predefined and can be cached, while other types are dynamically created.
So the choice is to use JPQL like:

JavaScript

Or CriteriaBuilder api to form a similar query:

JavaScript

Don’t forget to set the parameter values using query.setParameter(“id”, sf.id) for example.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement