简体   繁体   中英

Custom JpaRepository filter or query

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?

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM