0

I am trying to implement pagination and sorting in spring MVC. As per my understanding, we can use PagingAndSortingRepository or JpaRepository for same(http://springinpractice.com/2012/05/11/pagination-and-sorting-with-spring-data-jpa).

But both these use the default findAll method to do so.

I wish to create my own method and execute a custom query and perform the pagination as well as sorting on that(lets say search by category name and sort by creation date). I am not sure how to do this by using PagingAndSortingRepository or JpaRepository.

It will be great if I can have some sort of guidance to achieve this.

Thanks in advance.

Neil Stockton
  • 11,383
  • 3
  • 34
  • 29
Balwinder Singh
  • 2,272
  • 5
  • 23
  • 34

1 Answers1

1

With JPA you can do many combination of queries just by specifying method signatures. Please consult http://docs.spring.io/spring-data/jpa/docs/1.4.3.RELEASE/reference/html/jpa.repositories.html

In your repository interface you can

List<Person> findAll(); // this is standard
List<Person> findById(String id); // looking person that have specific Id
List<Person> findByNameLike(String name); // you can put the name "foo%"

If you want pagination and sorting...

Page<Person> findByNameLike(String name, PageRequest pageRequest);

And you use it like

int page = 0; // first page
int size = 10; // show 10 result max per page
Page personPage = repo.findByNameLike("A%", new PageRequest(page,size,Sort.Direction.ASC, "birthDate"));  // pagination for person with name, page 0, 10 item per page, and sorted by the person.birthDate.

Good luck

Ferdinand Neman
  • 680
  • 3
  • 6
  • Thanks for the explanation. Can you please share detailed tutorial for same? – Balwinder Singh Aug 25 '15 at 03:37
  • You can see this documentation http://docs.spring.io/spring-data/data-jpa/docs/1.0.0.M1/reference/html/#repositories.special-parameters Comes from this http://stackoverflow.com/questions/14120153/spring-data-jpa-apply-sorting-pagination-along-with-a-where-clause Its pretty straight forward – Ferdinand Neman Aug 25 '15 at 04:14