public interface ProductRepository extends JpaRepository<Product, Long> {
@Query("SELECT new com.stackoverflow.TotalProductDTO(p.category, COUNT(p.category)) FROM Product AS p GROUP BY p.category")
List<TotalProductDTO> countTotalProductsByCategory();
}
这将绑定 SELECT 对a的陈述 POJO . 指定的类需要具有与投影属性完全匹配的构造函数:
public class TotalProductDTO {
private String category;
private Long productsAvailable;
public TotalProductDTO(String category, Long productsAvailable) {
this.category = category;
this.productsAvailable = productsAvailable;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public Long getProductsAvailable() {
return productsAvailable;
}
public void setProductsAvailable(Long productsAvailable) {
this.productsAvailable = productsAvailable;
}
}
您可以使用下面的方法看到所需的json输出。
@RestController
public class ProductController {
private final ProductRepository productRepository;
public ProductController(ProductRepository productRepository) {
this.productRepository = productRepository;
}
@GetMapping(value = {"/availableProducts"})
public ResponseEntity<?> availableProducts() {
List<TotalProductDTO> totalProducts = productRepository.countTotalProductsByCategory();
return ResponseEntity.ok(totalProducts);
}
}
1条答案
按热度按时间gcuhipw91#
jpa规范允许我们以面向对象的方式定制结果。您可以使用jpql构造函数表达式来设置结果:
这将绑定
SELECT
对a的陈述POJO
. 指定的类需要具有与投影属性完全匹配的构造函数:您可以使用下面的方法看到所需的json输出。
因此,您将得到以下json: