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?
慕少森
相关分类