我有一个查询,它应该根据各种参数进行过滤;其中一个参数就是列表。如果列表中有条目,则应根据条目进行过滤;但如果列表为空/null,则不应对该字段进行任何过滤。
我的想法是这样的:
@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);发送null列表将抛出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。
发布于 2018-08-08 20:19:58
经过大量的试验和错误,我找到了一个可以接受的SpEL工作解决方案;我想有些人可能会发现它很有用:
@Query("select a from Alert a where a.date >= :startDate "
"and (:#{#countryIds == null} = true or (a.countryId in (:countryIds))) " +
"and (:#{#siteTypeIds == null} = true or (a.siteTypeId in (:siteTypeIds))) ")
List<Alert> findBy(@Param("startDate") Date startDate,
@Param("countryIds") Set<Long> countryIds,
@Param("siteTypeIds") Set<Long> siteTypeIds);作为参数发送的集合必须是null而不是空集。它产生一个可接受的SQL:
select alert0_.alertId as alertId1_0_, [...]
from alert alert0_
where alert0_.date >= '2018-01-01' and
(0 = 1 or alert0_.countryId in (1, 123)) and
(1 = 1 or alert0_.siteTypeId in (null));发布于 2018-08-08 19:23:11
对我来说,对于这种情况最好的解决方案是Criteria API,如果你不熟悉它,可以在这里找到一些信息:
发布于 2019-02-07 19:56:24
我也遇到了同样的问题,所以我在编写扩展解决方案时也使用了嵌入式参数。
@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}) ")其中,suppliers可以为空、为空或包含值,并且productIdentifier是包含productNumber和manufacturerId的嵌入式id,作为
@Param("productIdentifier") ProductIdentifier productIdentifier间隔也有效,范围从fromDate到null (永远)或untilDate。
https://stackoverflow.com/questions/51745277
复制相似问题