JPARepository 中本地查询的动态 WHERE

Dynamics WHERE to native query in JPARepository

我有本机查询 sql。我如何向这个 sql 添加动态“WHERE”。有时用户希望通过 idBran 过滤此结果。如果 metod 有参数 != null,我可以添加额外的 sql 代码吗?

@Query(value = "SELECT product.id_product as idProduct," +
            " product.product_name as productName," +
            " brand.id_brand as idBrand," +
            " brand.name_brand as nameBrand," +
            " type.name_type as nameType," +
            " type.short_type as shortType," +
            " product_image.url_image as img," +
            " product_image.alt_image as alt," +
            " NVL(AVG(product_review.score),0) as score," +
            " COUNT(product_review.textreview) as countComments" +
            " FROM product" +
            " LEFT JOIN product_review ON product.id_product=product_review.id_product" +
            " JOIN brand ON product.id_brand=brand.id_brand" +
            " JOIN type ON product.id_type=type.id_type" +
            " JOIN product_image ON product.id_product=product_image.id_product" +
            " GROUP BY product.id_product",
            countQuery = "SELECT count(*) FROM product",
            nativeQuery = true)
    Page<ProductsToListing> getAllProductsToListing(Pageable pageable);

尝试将以下 WHERE 子句添加到您的查询中:

WHERE 1=1 and (:idBrand is null or brand.id_brand = :idBrand)

其中 idBrand 是存储库方法中的参数,可以是 null 这样 WHERE 子句将被停用。如果在 idBrand 中传递非空值,则 WHERE 子句将被激活。

Page<ProductsToListing> getAllProductsToListing(@Param("idBrand") Integer idBrand, Pageable pageable); //supposing idBrand is an integer