使用单个查询的sql计数类别

qaxu7uf2  于 2021-07-24  发布在  Java
关注(0)|答案(1)|浏览(342)

我想创建一个spring数据jpa请求,从rest api返回以下结果:

[ {category: “Laptop”, productsAvailable: 2}, {category: pc,
productsAvailable: 1}]

IDCategoryDate1Laptop2PC3笔记本电脑
如何用一个sql请求实现这个功能?我可以使用两个sql查询,但我想使用一个。

gcuhipw9

gcuhipw91#

jpa规范允许我们以面向对象的方式定制结果。您可以使用jpql构造函数表达式来设置结果:

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);
    }
}

因此,您将得到以下json:

[
   {
      "category":"laptop",
      "productsAvailable":2
   },
   {
      "category":"pc",
      "productsAvailable":1
   }
]

相关问题