Spring 启动:切片/可分页未根据页面返回正确的块



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

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

但是,当我通过PageRequest.of(1, 1)创建Pageable对象时,这总是导致每次只返回第一项,但我已经通过调用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 --#pageablen",
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);
}
}

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

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

Slice<Foo> findByValidUntilIsNullOrValidUntilBefore(Date currentDate, Pageable pageable); // or can return a List<Foo>

你能尝试用页面对象代替切片吗?

步骤 1 - 创建页面大小

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

步骤-2

Page <Foo> findAllInactive(Date currentDate, Pageable page2);

最新更新