在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);
}
}
現在,當客戶端發送一個包含分頁參數的請求時,你的應用程序將返回分頁的數據。