写在前面
这里有两个实现
一、实现一
package tonels.util;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import java.util.ArrayList;
import java.util.List;
public interface PageUtil {
/** * Create a {@link org.springframework.data.domain.Page} from a {@link java.util.List} of objects * * @param list List数据 * @param pageable 分页参数. * @param <T> 包含数据 * @return page */
static <T> Page<T> createPageFromList(List<T> list, Pageable pageable) {
if (list == null) {
throw new IllegalArgumentException("list不能为空");
}
int startOfPage = pageable.getPageNumber() * pageable.getPageSize();
if (startOfPage > list.size()) {
return new PageImpl<>(new ArrayList<>(), pageable, 0);
}
int endOfPage = Math.min(startOfPage + pageable.getPageSize(), list.size());
return new PageImpl<>(list.subList(startOfPage, endOfPage), pageable, list.size());
}
}
使用
@GetMapping("/toPage2")
public ResultBean toPage2( @RequestParam(defaultValue = "1") int page,
@RequestParam(defaultValue = "20") int rows) {
Pageable pageable = PageRequest.of(page - 1, rows);
List<CustomersEntity> all = customerRepo.findAll();
Page<CustomersEntity> pageFromList = PageUtil.createPageFromList(all, pageable);
return ResultBean.ok(pageFromList.getTotalPages(),pageFromList.getTotalElements(),pageFromList.getContent());
}
一、实现二
package tonels.util;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import java.util.ArrayList;
import java.util.List;
public class PageUtilClass {
// todo 这里比较下 当工具类定义为 interface 和 class 的区别
// interface 更方便解耦,
public static <T> Page<T> createPageFromList(List<T> list, Pageable pageable) {
if (list == null) {
throw new IllegalArgumentException("To create a Page, the list mustn't be null!");
}
int startOfPage = pageable.getPageNumber() * pageable.getPageSize();
if (startOfPage > list.size()) {
return new PageImpl<>(new ArrayList<>(), pageable, 0);
}
int endOfPage = Math.min(startOfPage + pageable.getPageSize(), list.size());
return new PageImpl<>(list.subList(startOfPage, endOfPage), pageable, list.size());
}
}
使用
@GetMapping("/toPage3")
public ResultBean toPage3( @RequestParam(defaultValue = "1") int page,
@RequestParam(defaultValue = "20") int rows) {
Pageable pageable = PageRequest.of(page - 1, rows);
List<CustomersEntity> all = customerRepo.findAll();
Page<CustomersEntity> pageFromList = PageUtilClass.createPageFromList(all, pageable);
return ResultBean.ok(pageFromList.getTotalPages(),pageFromList.getTotalElements(),pageFromList.getContent());
}