在Java中实现Pageable接口,通常是为了处理分页数据
CustomPageRequest
的类:import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
public class CustomPageRequest implements Pageable {
private int page;
private int size;
private Sort sort;
public CustomPageRequest(int page, int size) {
this.page = page;
this.size = size;
}
public CustomPageRequest(int page, int size, Sort sort) {
this.page = page;
this.size = size;
this.sort = sort;
}
@Override
public int getPageNumber() {
return page;
}
@Override
public int getPageSize() {
return size;
}
@Override
public long getOffset() {
return (long) page * size;
}
@Override
public Sort getSort() {
return sort;
}
@Override
public Pageable next() {
return new CustomPageRequest(getPageNumber() + 1, getPageSize(), getSort());
}
// ... 其他方法
}
findAll
的方法,该方法接受一个CustomPageRequest
对象作为参数,并返回一个分页的结果:import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class MyService {
// ... 其他代码
public Page<MyEntity> findAll(CustomPageRequest pageRequest) {
// 获取分页参数
int page = pageRequest.getPageNumber();
int size = pageRequest.getPageSize();
Sort sort = pageRequest.getSort();
// 查询数据库并获取分页数据
List<MyEntity> entities = myRepository.findAll(page, size, sort);
// 计算总记录数(这里需要查询数据库)
long totalElements = myRepository.count();
// 创建并返回分页结果
return new PageImpl<>(entities, pageRequest, totalElements);
}
}
findAll
方法,并将分页请求传递给它:import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class MyController {
@Autowired
private MyService myService;
@GetMapping("/my-entities")
public Page<MyEntity> getMyEntities(@RequestParam("page") int page,
@RequestParam("size") int size,
@RequestParam(value = "sort", required = false) String sort) {
CustomPageRequest pageRequest = new CustomPageRequest(page, size, Sort.by(sort));
return myService.findAll(pageRequest);
}
}
现在,当客户端发送一个包含分页参数的请求时,你的应用程序将返回分页的数据。