自定义JpaRepository过滤器或查询

时间:2015-11-22 18:00:44

标签: java spring

我使用Posts JpaRepository函数获得每页findAll()的所有Interfce限制为10。但是,我想在PostType中创建一个自定义函数,只使用public interface PostRepository extends JpaRepository <Post, Integer> { } 等于2的记录。

我的界面类:

@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);*/
    }

我这样用:

findOnlyQuestions()

通过上面的代码,我收到了所有帖子。我需要使用自定义@Query来获取每页的所有问题。

(只有部分帖子是问题)

我想我在某个地方看到了我可以使用Gamma(x) = x^(a-1) * e^-x注释编辑查询并实现它。你觉得怎么样?

1 个答案:

答案 0 :(得分:1)

您实际上可以使用具有特殊名称的方法:

Page<Post> findByPostTypeEqual(Pageable pageable, int postType);

因此,当您调用方法时,只需传递2。

不确定它是否有效(当你想限制获取的记录数时它会起作用),但也尝试这样:

Page<Post> findByPostTypeEqual2(Pageable pageable);

使用@Query注释,您将拥有:

@Query("select p from Post p where p.postType = 2")
Page<Post> findByPostType(Pageable pageable);