0

在我的 PSQL DB 中,我存储了两个对象,我想在其单独的页面/切片上检索每个项目。我试图通过传入以下 Page 对象来实现这一点:

PageRequest.of(0,1)第一项和PageRequest.of(1, 1)第二项。

但是,当我通过创建Pageable对象时PageRequest.of(1, 1),这总是导致每次只返回第一个项目,但我通过调用确认这两个项目确实存在repo.findAll()

我做错了什么?

我的服务层调用如下所示:

 @Transactional
  public Slice<Foo> findAllInactive(Pageable pageable) {
    return repo.findAllInactive(new Date(), pageable));
  }

我的回购是:

@Repository
public interface FooRepository extends JpaRepository<Foo, String> {
  
      value =
          "SELECT * FROM fooschema.foo i WHERE i.valid_until < :currentDate OR i.valid_until IS NULL --#pageable\n",
      nativeQuery = true,
      countQuery = "SELECT count(*) FROM fooschema.foo i")
  Slice<Foo> findAllInactive(@Param("currentDate") Date currentDate, Pageable pageable);
}

如果有什么不同,这里是测试调用

  @Autowired private MockMvc mvc;

  @Test
  void testStuff() throws Exception {
    // two elements added....

    ResultActions resultActions =
            mvc.perform(
                    get("/foo")
                            .param("page", "1")
                            .param("size", "1"))// should return the second element, but returns the first
                    .andExpect(status().isOk())
                    .andExpect(content().contentType("application/json")); 
  }

和控制器

@RestController
@RequestMapping("/foo")
public class FooController {

  @GetMapping
  @ApiImplicitParams({
    @ApiImplicitParam(
        name = "page",
        dataType = "int",
        paramType = "query",
        value = "Page you want to retrieve",
        defaultValue = "0"),
    @ApiImplicitParam(
        name = "size",
        dataType = "int",
        paramType = "query",
        value = "Number of foo per page.",
        defaultValue = "10"))
  public Slice<Foo> getFoo(Pageable pageable) {
        return service.findAllInactive(pageable);
    }
}
4

2 回答 2

0

您可以尝试使用 Page 对象而不是 Slice。

第 1 步 - 创建页面大小

Pageable page1 = PageRequest.of(0, 1);
Pageable page2 = PageRequest.of(1, 1);

第2步

Page <Foo> findAllInactive(Date currentDate, Pageable page2);
于 2021-06-18T12:20:54.373 回答
0

Anshul 的评论让我走上了正轨,最后,似乎创建派生查询,如此处所述:https ://www.baeldung.com/spring-data-derived-queries有效。

最后,以下内容为我工作:

Slice<Foo> findByValidUntilIsNullOrValidUntilBefore(Date currentDate, Pageable pageable); // or can return a List<Foo>
于 2021-06-21T07:40:32.003 回答