org.springframework.data.domain.PageImpl 无法转换为

Java 新手。在我的项目中,我通过 findAll(spec) 获取数据,如下所示:


public interface ProductRepository extends JpaRepository<Product, Long> {

    List<Product> findAll(Specification<Product> spec);

在控制器中,我将响应转换为 DTO,如下所示:(ProductResponse 是一个 DTO)


private List<ProductResponse> convertProductListToResponse(List<Product> products) {


    List<ProductResponse> productResponseList = new ArrayList<ProductResponse>();

    for(int i = 0; i < products.size(); i++) {

        ProductResponse productResponse = new ProductResponse();

            productResponse.convert(products.get(i));

            productResponseList.add(productResponse);

    }


    return productResponseList;


}


@PostMapping("getProducts/{page}")

public List<ProductResponse> getAllProducts(@PathVariable("page") int page) {

    ProductSpecification nameSpecification = new ProductSpecification(new SearchCriteria("title", ":", "First Product"));

    // Service simply uses repository method:

    List<Product> filterProducts = productService.findAll(Specification.where(nameSpecification));


    List<ProductResponse> productResponseList = this.convertProductListToResponse(filterProducts);

    return productResponseList;

}

然后我决定通过分页获取数据,所以我更改了存储库:


public interface ProductRepository extends PagingAndSortingRepository<Product, Long> {

     List<Product> findAll(Specification<Product> spec, Pageable pageable);

现在我收到以下错误:


java.lang.ClassCastException: org.springframework.data.domain.PageImpl cannot be cast to com.vendo.app.entity.Product

然后我直接在控制器中输出响应(filterProducts),并发现响应结构如下:


[ { "content": [

        { "id": 1, "deleted": false, "title": "First Product", ...

        ....// array of product objects

我实在不明白,响应类型为List的方法怎么会返回这样的响应?如何从此响应中获取产品列表并将其转换为 DTO?


饮歌长啸
浏览 325回答 3
3回答

子衿沉夜

基本上默认findAll有 2 个变体如果您想转换Page<Product>为简单List<Product>productRepository.findAll(PageRequest.of(0,&nbsp;count)).toList();

陪伴而非守候

在findAll方法中你应该返回Page<Product>而不是List<Product>

跃然一笑

我意识到我的错误是使用 List 而不是 Page 作为 findAll 的返回类型。存储库应如下所示:  Page<Product> findAll(Specification<Product> spec, Pageable pageable);控制器应如下所示:    @PostMapping("getProducts/{page}")public List<ProductResponse> getAllProducts(@PathVariable("page") int page) {         Pageable productPageable = PageRequest.of(0, page);            ProductSpecification nameSpecification = new ProductSpecification(new SearchCriteria("title", ":", "First Product"));     Page<Product> filterProducts = productService.findAll(Specification.where(nameSpecification), productPageable);     List<ProductResponse> productResponseList = this.convertProductListToResponse(filterProducts.getContent());         return productResponseList; }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java