【问题标题】:Dynamics WHERE to native query in JPARepository动态 WHERE 到 JPARepository 中的本机查询
【发布时间】:2021-10-23 16:06:58
【问题描述】:

我有本机查询 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);

【问题讨论】:

  • idBran 是你想在这个“动态”中传递的唯一参数吗?

标签: java sql spring-boot spring-data-jpa


【解决方案1】:

尝试将以下 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

【讨论】:

    猜你喜欢
    • 2019-11-11
    • 1970-01-01
    • 2017-04-15
    • 2022-01-10
    • 2019-07-26
    • 1970-01-01
    • 2014-05-14
    • 1970-01-01
    • 2021-01-19
    相关资源
    最近更新 更多