JPQL 如何检查列表是否包含输入列表中的任何项目

问题描述 投票:0回答:1

我需要检查列表是否包含输入列表中的任何项目。

@Query("""
SELECT items FROM ItemEntity items WHERE items.type = :type
AND (coalesce(:idList) IS NULL OR items.id IN (:idList)) <- this is ok
AND (coalesce(:sourceList) IS NULL OR :sourceList MEMBER OF items.sources) <-- this is not
""")
List<Items> findItems(@Param("type") String type, @Param("idList") List<String> idList,
List<String> sourceList);

sourceList 是包含 ['Canada', 'Sydney',...] 的字符串列表

与我之前的存储库中的JPA查询命名参数问题类似,当列表中只有一项时它会起作用,当列表中有超过1项时我会得到相同的错误:

java.lang.IndexOutOfBoundsException: Index: 0 at java.base/java.util.Collections$EmptyList.get(Collections.java:4586) ~[na:na]
所以基本上我需要检查数据库中的列表是否包含输入列表中的任何(不是全部)项目。

示例:

项目:

    齿轮
来源:

    悉尼
  • 德国
我对 sourceList 的输入是 ['加拿大', '悉尼']

然后它应该返回项目 Gear。

编辑

根据安德烈·潘菲洛夫

SELECT items FROM ItemEntity items WHERE items.type = :type AND (coalesce(:idList) IS NULL OR items.id IN (:idList)) <- this is ok AND (coalesce(:sourceList) IS NULL OR exists (select 1 from items.sources s where s in (:sourceList)))
    
java spring-boot jpql
1个回答
0
投票
如果您使用 Spring,您可以通过以下方式使用 SpEl 来完成:

@Query("SELECT e FROM EspacioCv e " + "WHERE (:#{#listaPlataformas == null || #listaPlataformas.isEmpty()} = true OR e.plataforma.id IN :listaPlataformas) " + "AND (e.esCuestionario = :esCuestionario) " + "AND (:#{#idEstadoEspacios == null || #idEstadoEspacios.isEmpty()} = true OR e.estadoEspacio.id IN :idEstadoEspacios) " + "AND (:#{#cursosAcademicos == null || #cursosAcademicos.isEmpty()} = true OR e.cursoAcademico.id IN :cursosAcademicos)") List<EspacioCv> findAllByPlataformaCursoAcademicoCuestionarioYEstadoEspacioDinamico( @Param("listaPlataformas") List<String> listaPlataformas, @Param("esCuestionario") Boolean esCuestionario, @Param("idEstadoEspacios") List<String> idEstadoEspacios, @Param("cursosAcademicos") List<String> cursosAcademicos);
我希望这有帮助!

© www.soinside.com 2019 - 2024. All rights reserved.