簡體   English   中英

當參數為 null 時如何從本機查詢中排除 where 條件

[英]How to exclude the where condition from the native query when the parameter is null

我正在為我的應用程序使用 spring boot v2.6.1 和 Postgres DB。 我在我的一個存儲庫中有以下方法。

@Query(value = "SELECT * from subscriptions s " +
            "WHERE (:merchantID is NULL OR s.created_by = cast(:merchantID AS text)) " +
            "AND (:status is NULL or s.status IN (:status))", nativeQuery = true)
    List<Subscription> findWithStatus (@Param("merchantID")String merchantID, @Param("status") List<String> status);

當參數“狀態”不是 null 時,它工作正常。 但是當它是 null 時,它會引發異常

org.postgresql.util.PSQLException:錯誤:運算符不存在:字符變化 = bytea

由此,我了解到即使指定的參數是 null,該條件也不會從查詢中排除。 我認為問題在於檢查參數是否為 null ,即:status 為 null ,所以我只是將列表參數更改為String並傳遞了 null 值,仍然拋出相同的異常。 所以問題不在於:status is null而是查詢中的 IN 運算符。

當參數為 null 時,如何用 IN 運算符排除這種情況?

如果要使用此本地查詢近似值,一種解決方案是添加一個額外的 Boolean 參數,指示狀態列表是否為 null。

@Query(value = "SELECT * from subscriptions s " +
            "WHERE (:merchantID is NULL OR s.created_by = cast(:merchantID AS text)) " +
            "AND (:statusIsNull or s.status IN (:status))", nativeQuery = true)
    List<Subscription> findWithStatus (@Param("merchantID")String merchantID, @Param("statusIsNull") Boolean statusIsNull, @Param("status") List<String> status);

所以 function 調用將是這樣的:

Boolean statusIsNull = (statusList == null || statusList.isEmpty()) ? true : false;

List<Subscription> subscriptionList = findWithStatus (merchantID, statusIsNull, statusList);

但我真的推薦使用JPA Criteria API來構建動態查詢。

問候。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM