Home > Net >  Combining JPA specification with pagination
Combining JPA specification with pagination

Time:11-30

I have a JPA specification that needs to be split up in two, but also support backend pagination. I am unsure how to accomplish this.

For example, I have Employess that can be of two types Teachers and Carers. I need to perform a filtered search (the exact search) on both and return a single unionized response, that can support pagination. Although I know how to perform the two requests, I don't know how to process the pagination when combining JPA specifications. Any hints?

class EmployeeEntity {
  private Long id;
  private EmployeeType type;
  private String name;

} 

CodePudding user response:

Have you tried JpaRepository or ListPagingAndSortingRepository or PagingAndSortingRepository as they allow pagination and creating methods like findAllByType(...) may solve your problem. Andd for combining results, you can use HQL type query to write a single query or create 2 queries to DB and put them in a single list/set before you return as result.

CodePudding user response:

You can handle Pagination with multiple specifications by using Criteria API. Example:

DetachedCriteria detachedCriteria = DetachedCriteria.forClass(EmployeeEntity.class, "employee");

Now suppose you want to filter Employee by EmployeeType which is some different entity:

detachedCriteria.createAlias("employee.type", "employeeType");
detachedCriteria.add(Restrictions.eq("employeeType.name", string (example: "Teachers")));

Similar way you can add more specifications, and for pagination, you can do this:

Integer pageNumber = (Integer.valueOf(page_number)-1) * 10;

and then you can pass all this data using the:

resultList = findByCriteria(detachedCriteria,pageNumber,page_size);

which will return your result based on the specification and pagination based on page_number and page_size

  • Related