Thursday 27 October 2016

Implement pagination with Spring-data-jpa framework

Today I have learnt a new way of dealing with pagination using Spring-data-jpa framework

 <dependency>  
   <groupId>org.springframework.data</groupId>  
   <artifactId>spring-data-jpa</artifactId>  
   <version>1.10.4.RELEASE</version>  
 </dependency>  

In the repository class

 @Query("Select E from Employee E where E.age >=:age")  
 public Page<Employee> findByAge(@Param("age")int age, Pageable pageable);  

Usage example. Pretty straight forward.

 Page<Employee> page = employeeRepo.findByAge(18, new PageRequest(0, 1, Direction.DESC, "age"));  
 if (page.getNumberOfElements() > 0){  
      return page.getContent().get(0);  
 }  
 return null;