简体   繁体   English

JPARepository 中本地查询的动态 WHERE

[英]Dynamics WHERE to native query in JPARepository

I have native query sql. How I can add dynamics "WHERE" to this sql. Sometimes user want filtr this result by idBran.我有本机查询 sql。如何将动态“WHERE”添加到此 sql。有时用户希望通过 idBran 过滤此结果。 Can I add to extra sql code if metod has parametr?= null?如果 metod 有参数,我可以添加额外的 sql 代码吗?= null?

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

Try to add to your Query the following WHERE clause:尝试将以下 WHERE 子句添加到您的查询中:

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

where idBrand is the parameter in your repository method which can be null and this way the WHERE clause will be deactivated.其中idBrand是存储库方法中的参数,可以是null ,这样 WHERE 子句将被停用。 If non-null value is passed in idBrand then the WHERE clause will be activated.如果在 idBrand 中传递了非空值,则 WHERE 子句将被激活。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM