views:

39

answers:

1

Can anyone suggest the correct syntax for a where clause using in applied to a list? The following query in an .hbm file generates a parse exception:

<query name="Nutrient.findNutrients1">
    <![CDATA[from Nutrient as nutrient where nutrient.id in elements(?)]]>
</query>

The exception follows:

PARSER.reportError(56) | line 2:95: expecting IDENT, found '?' SessionFactoryImpl.(395) | Error in named query: Nutrient.findNutrients1 org.hibernate.hql.ast.QuerySyntaxException: expecting IDENT, found '?' near line 2, column 95 [ from Nutrient as nutrient where nutrient.id in elements(?)

+1  A: 

Remove the elements part of your query:

<query name="Nutrient.findNutrients1">
    <![CDATA[from Nutrient as nutrient where nutrient.id in (:ids)]]>
</query>

And invoke it like this:

List<Long> vals = Arrays.asList(1L, 2L);

Query q = session.getNamedQuery("Nutrient.findNutrients1");
q.setParameterList("ids", vals);
List<Nutrient> result = q.list();
Pascal Thivent
Thanks for this. However, I'm not sure how to use named parameters in a query defined in an .hbm file - I thought you needed to do this through the session... Do you know if it can be done via .hbm?
Greg Harman
@Greg You can use either positional or named parameters in named queries. But that's not the important part anyway. I can remove it if you prefer :)
Pascal Thivent
@Pascal Rather than remove, would you mind adding a little bit to show how to pass in the named parameter in this context?
Greg Harman
@Gred I should have done that in my initial answer. See my update.
Pascal Thivent
@Pascal Sorry to be needy here, but would you also show a version of the query that uses positional parameters? (I'm sure I'm doing something silly, but it's just not parsing as I expect it to)
Greg Harman
@Greg Actually, there is no `Query#setParameterList(int, Collection)`, you'll have to use a named parameter.
Pascal Thivent
@Greg BTW, I tested this, works fine for me.
Pascal Thivent