New to Java. In my project I was getting data by findAll(spec) like this:
public interface ProductRepository extends JpaRepository<Product, Long> {
List<Product> findAll(Specification<Product> spec);
and in the controller, I was converting response into DTOs like this: (ProductResponse is a 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;
}
Than I decided to get data with pagination so I changed the repository:
public interface ProductRepository extends PagingAndSortingRepository<Product, Long> {
List<Product> findAll(Specification<Product> spec, Pageable pageable);
Now I get the following error:
java.lang.ClassCastException: org.springframework.data.domain.PageImpl cannot be cast to com.vendo.app.entity.Product
Than I output the response (filterProducts) directly in the controller and found a response structured like this:
[ { "content": [
{ "id": 1, "deleted": false, "title": "First Product", ...
....// array of product objects
I really don't understand, how can a method with response type of List return such a response? How can I get list of products from this response and convert into DTOs?
Thank you.
在findAll
方法中,您应该返回Page<Product>
而不是List<Product>
By the help of KamilW , I realized that my mistake was using List instead of Page for return type of findAll.
Repository should be as follows:
Page<Product> findAll(Specification<Product> spec, Pageable pageable);
and controller should be as follows:
@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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.