亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

僅當作為參數傳遞的 List 具有元素時才考慮 JPA 'where in'

僅當作為參數傳遞的 List 具有元素時才考慮 JPA 'where in'

開滿天機 2021-06-27 12:39:27
我有一個應根據各種參數進行過濾的查詢;這些參數之一是一個列表。如果列表中有條目,則應根據條目進行過濾;但如果列表為空/空,則不應對該字段進行任何過濾。我的想法是這樣的:@Query("select a from Alert a where a.date >= :startDate " +            "and (((:countryIds) is null) or a.countryId in (:countryIds)) " +            "and (((:typeIds) is null) or a.siteTypeId in (:typeIds)) ")List<Alert> findBy(@Param("startDate") Date startDate,                   @Param("countryIds") Set<Long> countryIds,                   @Param("typeIds") Set<Long> typeIds);發送空列表會拋出 NPE;發送一個空列表它會生成以下SQL,這是無效的where alert0_.date >= '2018-01-01' and                                                        ((1, 123) is null or alert0_.countryId in (1, 123))我也嘗試過使用 JPQL,and (((:countryIds) is empty) or a.countryId in (:countryIds))但是在嘗試編譯 JPQL(在應用程序啟動時)時它也不起作用:Caused by: org.hibernate.hql.internal.ast.QuerySyntaxException: ??? is not mapped    at org.hibernate.hql.internal.ast.util.SessionFactoryHelper.requireClassPersister(SessionFactoryHelper.java:171) 或者使用 SpEL: "and (:#{countryIds.size() > 0} or (a.countryId in (:countryIds))) " 但同樣,它不會編譯 JPQL。我想到的唯一解決方案是動態生成丑陋的 JPQL 或填充所有現有值countryIds,siteTypeIds這是低效的。JPA 實現是 Hibernate,數據庫是 MySQL。
查看完整描述

3 回答

?
ibeautiful

TA貢獻1993條經驗 獲得超6個贊

我遇到了同樣的問題,所以我使用嵌入式參數編寫擴展解決方案


@Query("from PartPrice where "

            + "customer in :#{#customers} and "

            + "( (:#{#suppliers == null || #suppliers.size() == 0} = true and supplier is null) or (:#{#suppliers != null && #suppliers.size() > 0} = true and supplier in :#{#supplier}) ) and "

            + " productIdentifier.manufacturerId = :#{#productIdentifier.manufacturerId} and productIdentifier.productNumber = :#{#productIdentifier.productNumber} and "

            + " ( (:#{#isAbsPrice} = true and abs_price is not null) or (:#{#isAbsPrice} = false and abs_price is null) ) "

            + " and (validUntil is null or validUntil >= :#{#fromDate}) and (:#{#untilDate == null} = true or validFrom <= :#{#untilDate}) ")

其中供應商可為空、為空或包含值,而 productIdentifier 是嵌入的 id,其中包含 productNumber 和制造商 ID 傳遞為


@Param("productIdentifier") ProductIdentifier productIdentifier

間隔也是有效的,從 fromDate 到 null(永遠)或 untilDate。


查看完整回答
反對 回復 2021-07-07
  • 3 回答
  • 0 關注
  • 198 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號