Inside org.springframework.data.jpa.repository.@Query
annotation I check if field in a collection and possibly ignore collection if it is empty:
@Query(""select e from #{#entityName} where e.type in :lst or 0 = :lstSize")
List<Entity> findByLst(@Param("lst") List<XEnum> lst, @Param("lstSize") int lstSize);
I call code as:
List<XEnum> lst = ...;
int lstSize = (lst == null) ? 0 : lst.size();
findByLst(lst, lstSize);
For Oracle DB in case of lst = null
Hibernate logged:
DEBUG [nio-8443-exec-4] org.hibernate.SQL
entity0_.type in (?) or 0=?
TRACE [nio-8443-exec-4] org.hibernate.type.EnumType
Binding null to parameter: [1]
TRACE [nio-8443-exec-4] org.hibernate.type.descriptor.sql.BasicBinder
binding parameter [2] as [INTEGER] - [0]
For case of lst = new LinkedList<>()
Hibernate logged:
DEBUG [nio-8443-exec-5] org.hibernate.SQL
entity0_.type in ( ) or 0=?
TRACE [nio-8443-exec-5] org.hibernate.type.descriptor.sql.BasicBinder
binding parameter [1] as [INTEGER] - [0]
ERROR [nio-8443-exec-5] org.hibernate.engine.jdbc.spi.SqlExceptionHelper
ORA-00936: missing expression
and it is syntactically invalid in SQL*PLUS also:
select 1 from dual where 1 in ();
Can I omit lstSize
and still check if collection is not provided - return all elements?
How can I deal with empty list and Oracle ()
syntax error?
Actually I have large JPQL expression that handle several cases of empty arguments with single call. My goal to keep simple method instead of writing several specialized methods, using if/else
or Critetia builder...
For example ignoring empty parameters can be archived with:
... and (e.field = :fieldVal or :fieldVal is null)
UPDATE Relevant resources:
- Passing empty list as parameter to JPA query throws error
- https://hibernate.atlassian.net/browse/HHH-8091 (Hibernate produces SQL - "in ()" - which is invalid in at least Oracle, MySQL and Postgres)