Spring data mongo pagination

2019-03-21 11:54发布

问题:

I want to implement pagination with Spring Data Mongo. There are many tutorials and docs suggest to use PagingAndSortingRepository, like this:

StoryRepo extends PagingAndSortingRepository<Story, String>{}

And so because PagingAndSortingRepository provides api for query with paging, I can use it like:

Page<Story> story = storyRepo.findAll(pageable);

My question is where actually is this findAll method here implemented? Do I need to write its implementation by myself? The StoryRepoImpl which implements StoryRepo needs to implement this method?

回答1:

You do not need to implement the method as when you autowired the Spring object PagingAndSortingRepository, it automatically implements the method for you.

Please note that since you are using Mongodb, you can extend MongoRepository instead.

Then in Spring, enable pagination using this:

@RequestMapping(value="INSERT YOUR LINK", method=RequestMethod.GET)
  public List<Profile> getAll(int page) {
    Pageable pageable = new PageRequest(page, 5); //get 5 profiles on a page
    Page<Profile> page = repo.findAll(pageable);
    return Lists.newArrayList(page);


回答2:

I got it working by writing my own implementations, something like this:

List<Story> stories = null;

Query query = new Query();
query.with(pageable);

stories = getTemplate().find(query, Story.class);

long total = getTemplate().count(query, Story.class);
Page<Story> storyPage = new PageImpl<Story>(stories, pageable, total);

return storyPage;

I'm working with spring data & mongodb, using mongo template to query data.



回答3:

The method is implemented by a store-specific class. For the Spring Data JPA module, it's SimpleJpaRepository. You usually let a DI container create instances for these repository interfaces. With Spring you'd activate Spring Data repositories by either using @EnableJpaRepository on a JavaConfig class or

<jpa:repositories base-package="com.acme.repositories" />

This will create a proxy instance for the repo, so that you can get it injected into your clients:

class MyClient {

  @Inject
  public MyClient(PersonRepository repository) {
    …
  }
}


回答4:

To paginate a query, you can use something like below:

public interface PersonRepository extends MongoRepository<Person, String> {
    Page<Person> findByFirstname(String firstname, Pageable pageable);
}

For more details, please refer to the second query in Example 6.6 in https://docs.spring.io/spring-data/mongodb/docs/1.2.0.RELEASE/reference/html/mongo.repositories.html