有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java组织。springframework。数据领域无法将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

谢谢


共 (1) 个答案

  1. # 1 楼答案

    KamilW的帮助下,我意识到我的错误是使用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;
    }