Search code examples
javaspring-bootjpanamed-parameters

JPA Query named parameter issue in Repository


I have this method in my repository:

@Query("""
SELECT items FROM ItemEntity items WHERE items.type = :type
AND (:idList IS NULL OR items.id IN :idList)
""")
List<Items> findItems(@Param("type") String type, @Param("idList") List<String> idList);

It works when idList is null or has only 1 item, but it gives me an IndexOutOfBoundsException when idList contains more than 1 item:

java.lang.IndexOutOfBoundsException: Index: 0
at java.base/java.util.Collections$EmptyList.get(Collections.java:4586) ~[na:na]

I don't know what's causing it.


Solution

  • Add parentheses like this:

    @Query("""
    SELECT items FROM ItemEntity items WHERE items.type = :type
    AND (:idList IS NULL OR items.id IN (:idList))
    """)