首页 > 解决方案 > 在 Java 中将 Pageable 转换为 List 时出错

问题描述

我已经编程返回产品页面。而且效果很好

这是一个例子:

productServiceImpl.java

public Page<ProductDTO> findProduct(Pageable pageable) {

   Page<ProductDTO> page = this.repository.findProduct(pageable);
           
   return page;
       
}

produtoRepositoryImpl.java


        public Page<ProductDTO> obterProdutoFilho(Pageable pageable) {

        StringBuilder sb = new StringBuilder();

        sb.append("     SELECT DISTINCT P.ID  ");
        sb.append("                   , P.NAME  ");
        sb.append("                   , C.ID AS PRODUCT_ID  ");

        sb.append("     FROM  ");
        sb.append("                     {database_user}.PRODUCT_A P,   ");
        sb.append("                     {database_user}.PRODUCT_B C   ");
        sb.append("     WHERE   ");
        sb.append("                      P.ID = C.product_r_ID  ");


        Map<String, Type> mapFields = new HashMap<>();
        mapFields.put("id", StandardBasicTypes.LONG);
        mapFields.put("name", StandardBasicTypes.STRING);
        mapFields.put("product_id", StandardBasicTypes.LONG);

        Map<String, Object> mapParams = new HashMap<>();

        Page<ProductDTO> page = super.page(this.em, sb, pageable, mapParams, mapFields, true, ProductDTO.class);

        return page;
    }

尝试转换为列表时,出现错误。

java.util.Collections$UnmodifiableRandomAccessList 不能转换为 org.springframework.data.domain.Page

我试着这样投。

    @Override
    public Page<ProductDTO> findProduct(Pageable pageable) {

        @SuppressWarnings("unchecked")
        Page<ProductDTO> page = (Page<ProductDTO>) this.repository.findProduct(pageable).getContent();

        return page;
    }

谢谢你,从现在开始

标签: java

解决方案


此返回 Page 对象:

this.repository.findProduct(pageable)

而这个返回 List 对象:

this.repository.findProduct(pageable).getContent()

那么这应该可以工作(假设你想在你的方法中返回列表):

public List<ProductDTO> findProduct(Pageable pageable) {
    return this.repository.findProduct(pageable).getContent();
}

推荐阅读