Reputation: 5070
I am getting all Posts
per page with a limit of 10 with use of JpaRepository
findAll()
function. However, I would like to make a custom function in the Interfce
to take only those records which have PostType
equals to 2.
My interface class:
public interface PostRepository extends JpaRepository <Post, Integer> {
}
I use it like this:
@RequestMapping(value = "/posts", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
Page<Post> getAllPosts(@RequestParam int page) {
//int page=1;
PageRequest request =
new PageRequest(page - 1, PAGE_SIZE, Sort.Direction.DESC, "CreationDate");
return postRepository.findAll(request);
/* List<Post> list = (List<Post>) postRepository.findAll();
return new ResponseEntity<List<Post>>(list, HttpStatus.OK);*/
}
With the above code, I am getting all posts. I need to use my custom findOnlyQuestions()
to get all questions per page.
(Only some of the posts are questions)
I think I saw somewhere I could edit query with a @Query
annotation and achieve it like that. What do you think?
Upvotes: 0
Views: 718
Reputation: 14806
You could actually use a method with special name:
Page<Post> findByPostTypeEqual(Pageable pageable, int postType);
So when you call a method, just pass 2.
Not sure whether it will work (it works when you want to limit number of fetched records), but try like this too:
Page<Post> findByPostTypeEqual2(Pageable pageable);
With @Query annotation you would have:
@Query("select p from Post p where p.postType = 2")
Page<Post> findByPostType(Pageable pageable);
Upvotes: 2