Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing empty list as parameter to JPA query throws error

If I pass an empty list into a JPA query, I get an error. For example:

List<Municipality> municipalities = myDao.findAll();  // returns empty list em.createQuery("SELECT p FROM Profile p JOIN p.municipality m WHERE m IN (:municipalities)")     .setParameter("municipalities", municipalities)     .getResultList(); 

Because the list is empty, Hibernate generates this in SQL as "IN ()", which gives me error with Hypersonic database.

There is a ticket for this in Hibernate issue tracking but there are not many comments/activity there. I don't know about support in other ORM products or in JPA spec either.

I don't like the idea of having to manually check for null objects and empty lists every time. Is there some commonly known approach/extension to this? How do you handle these situations?

like image 883
Tuukka Mustonen Avatar asked Mar 21 '10 22:03

Tuukka Mustonen


People also ask

Is empty in JPA query?

The IS EMPTY operator is the logical equivalent of IS NULL, but for collections. Queries can use IS EMPTY operator or IS NOT EMPTY to check whether a collection association path resolves to an empty collection or has at least one value.

What is the use of @query in JPA?

Understanding the @Query Annotation The @Query annotation can only be used to annotate repository interface methods. The call of the annotated methods will trigger the execution of the statement found in it, and their usage is pretty straightforward. The @Query annotation supports both native SQL and JPQL.

Why do we use @query annotation?

The @Query annotation takes precedence over named queries, which are annotated with @NamedQuery or defined in an orm. xml file. It's a good approach to place a query definition just above the method inside the repository rather than inside our domain model as named queries.

What is @query annotation in spring boot?

The @Query annotation declares finder queries directly on repository methods. While similar @NamedQuery is used on domain classes, Spring Data JPA @Query annotation is used on Repository interface. This frees the domain classes from persistence specific information, which is a good thing.


1 Answers

According to the section 4.6.8 In Expressions from the JPA 1.0 specification:

There must be at least one element in the comma separated list that defines the set of values for the IN expression.

In other words, regardless of Hibernate's ability to parse the query and to pass an IN(), regardless of the support of this syntax by particular databases (PosgreSQL doesn't according to the Jira issue), you should use a dynamic query here if you want your code to be portable (and I usually prefer to use the Criteria API for dynamic queries).

like image 127
Pascal Thivent Avatar answered Sep 19 '22 22:09

Pascal Thivent