16 February 2009

Hibernate gotcha: in clause with positional and named query parameters

Here's a gotcha that can break JPA QL queries with an IN clause when using Hibernate as the persistence provider. The problem happens when you use positional parameters rather than named parameters.

Code such as the following will break with positional parameters:
List states = widgetService.findSomeWidgetStates();
Query q = entityManager.createQuery("select count(w) from Widget w where w.state in (?)");
q.setParameter(1, states);
with the error message:
Caused by: java.lang.IllegalArgumentException: Can not set java.lang.Integer field example.Widget.id to....
But if you change to named parameters, as in:
Query q = entityManager.createQuery("select count(w) from Widget w where w.state in (:widgetStates)");
q.setParameter("widgetStates", states);
Everything just works. So it seems named parameters are worth a little extra typing.

No comments:

Post a Comment