How to query data via Spring data JPA with user defined offset and limit (Range)
We can do this with Pagination and by setting the database table column name, value & row counts as below:
@Transactional(readOnly=true)
public List<String> queryEmployeeDetails(String columnName,String columnData, int startRecord, int endRecord) {
Query query = sessionFactory.getCurrentSession().createQuery(" from Employee emp where emp.col= :"+columnName);
query.setParameter(columnName, columnData);
query.setFirstResult(startRecord);
query.setMaxResults(endRecord);
List<String> list = (List<String>)query.list();
return list;
}
Your approach didn't work, because new PageRequest(0, 10);
doens't do what you think. As stated in docs, the input arguments are page
and size
, not limit and offset.
As far as I know (and somebody correct me if I'm wrong), there is no "out of the box" support for what you need in default SrpingData repositories. But you can create custom implementation of Pagable
, that will take limit/offset parameters. Here is basic example - Spring data Pageable and LIMIT/OFFSET
If I am understanding your problem correctly, you want your repository to allow user to
- Provide criteria for query (through
Specification
) - Provide column to sort
- Provide the range of result to retrieve.
If my understanding is correctly, then:
In order to achieve 1., you can make use of JpaSpecificationExecutor
from Spring Data JPA, which allow you to pass in Specificiation
for query.
Both 2 and 3 is achievable in JpaSpecificationExecutor
by use of Pagable
. Pageable
allow you to provide the starting index, number of record, and sorting columns for your query. You will need to implement your range-based Pageable
. PageRequest
is a good reference on what you can implement (or you can extend it I believe).