繁体   English   中英

自定义JpaRepository过滤器或查询

[英]Custom JpaRepository filter or query

我使用JpaRepository findAll()函数获得每页所有Posts的限制为10。 但是,我想在Interfce创建一个自定义函数,以仅接受PostType等于2的那些记录。

我的界面类:

public interface PostRepository extends JpaRepository <Post, Integer> {

}

我这样使用它:

@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注释的查询并实现该目标。 你怎么看?

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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