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?
3 回答
子衿沉夜
TA贡献1828条经验 获得超3个赞
基本上默认findAll
有 2 个变体
如果您想转换Page<Product>
为简单List<Product>
productRepository.findAll(PageRequest.of(0, count)).toList();
跃然一笑
TA贡献1826条经验 获得超6个赞
我意识到我的错误是使用 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; }
添加回答
举报
0/150
提交
取消