上一篇 SpringData中Page对象的架构设计

一、代码示例

   @GetMapping("/listTopage")
    public Page listtoPage(){
   
        List<CustomerDTO> customerDTOS = customerMapper.toCustomerDto(customerService.findAll());
        PageImpl page = new PageImpl(customerDTOS, PageRequest.of(0, 20), customerDTOS.size());
        return page;
    }

可以参考下代码实现(部分)

public PageImpl(List<T> content, Pageable pageable, long total) {
   

		super(content, pageable);

		this.total = pageable.toOptional().filter(it -> !content.isEmpty())//
				.filter(it -> it.getOffset() + it.getPageSize() > total)//
				.map(it -> it.getOffset() + content.size())//
				.orElse(total);
	}

注意::这里的处理,只完成了当前页的数据page封装,并不准确

二、纠正一下,上文的处理是不正确的,可参考以下

封装工具类

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("/to-page")
    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());
    }

即可完成正确处理

这里,还有List的很多操作