简体   繁体   中英

JPA query parameter IN or IS NULL

I have an issue with this simple query:

@Query("SELECT c FROM Cat c WHERE c.id IN (:idCat) OR :idCat IS NULL")
List<Cat> getAllCatWithOrWithoutId(@Param("idCat")List<String> idCat);  

Which queried in a list, or, if the id is not mentionned, select all cats in table (idCat is optional actually). It seems working when it's an "=" operator instead of IN but when I run the query I have the error message is: "invalid relational operator". Even if I try with a native query. I tried to replace idCat value by single value (it worked), or by null (it worked too), but not when I put several values.

Is it something wrong in syntax or is it simply impossible with an IN statement?

When you provide a filled list, your second part of the query ( OR:idCat IS NULL ) is translated to a list of values to compare to " IS NULL ".

As stated on JSR-338 , chapter 4.6.11, " [a] null comparison expression tests whether or not the single-valued path expression or input parameter is a NULL value ", so it is not expected to support a filled list as an argument. To check lists, there is the " IS [NOT] EMPTY " expression, but it expects a collection_valued_path_expression and it is not your case.

I've stumbled sometimes with strange behavior of some persistence providers where they supported (anti-spec) this kind of comparison if you surround the parameter with parenthesis, but, again, you can not rely on it for future evolutions.

The best approach in your case would be define two different JPQLs or methods to deal with your both desired scenarios.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM