When I make a request about all the news that I have in my database I use a PageRequest like this:
public Page<StatusUpdate> getPageSiteUser(int pageNumber) {
PageRequest request = new PageRequest(pageNumber-1, pageSize, Sort.Direction.DESC, "added");
return statusUpdateDao.findAll(request);
}
And it shows all the news in each page sorted in perfect order.
But now, I want to select the news created by one user, in the same Pageable format (not all the news) and I do not find how to do it, so I must be making a stupid mistake somewhere... it should be something like...
public Page<StatusUpdate> findMyStatusUpdates(Long user_id, int pageNumber) {
PageRequest request = new PageRequest(pageNumber-1, pageSize, Sort.Direction.DESC, "added");
return statusUpdateDao.findAll(request);
}
Please, answer with a link to the the theory if you can. The documentation talks about sorting, not making the actual selection (enter link description here)
You can combine a query, to filter by the user, with a pageable request. The query can be created by Spring based on the method name.
Take a look to the documentation:
Spring data JPA Query creation
Using Pageable, Slice and Sort in query methods
In your case, without seeing your code, I guess you only need to include in your repository a method like:
public interface StatusUpdateRepository extends Repository<StatusUpdate, Long> {
//finBy<column_name>
Page<User> findByUser(Long userId, Pageable pageable);
}
You can also send a PageRequest to an existing filter in your repo. You can create a repository method, filter them according to your business need.
Let's say you would like to find posts by supplying a user, status attributes and then order them by their creation date in descending order.
One might not desire all posts being included in the Page object while sending them to a Pager, before adding to the Model model.
This is simply equivalent to a sql query as such:
select * from Post where user=user and status=status order by createdAt desc
--
public interface BlogRepository extends PagingAndSortingRepository<Post, Long> {
Page<Post> findByUserAndStatusOrderByCreatedAtDesc(PageRequest pageRequest,
User user, boolean status);
}
and in your controller, use its implementation(postService) along with a new PageRequest object like:
Page<Post> filteredPosts = postService.findByUserAndStatusOrderByCreatedAtDesc(PageRequest.of(evalPage, evalPageSize), user, status);
this works fine for 2.x.x; whereas you better use below for 1.x.x
Page<Post> filteredPosts =
postService.findByUserAndStatusOrderByCreatedAtDesc(new PageRequest(evalPage,
evalPageSize), user, status);
This repo guided me up to a certain point on this matter with paging logic etc.
Just had to change from ModelView to Model in the controller's argument and returned String (template's name) instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With