How can I make a named query with IN actually work?
class X {
Y y; // manyToOne
}
class Y {
Long id;
}
@NamedQuery(name = "someName", query = "from X where y.id in :ids")
I have public, table, entity and all other things on the Entities but I didn't wrote them here.
TypedQuery<X> query = getEntityManager().createNamedQuery("someName", X.class);
query.setParameter("ids", someListOfLongs); // HERE I GET THE ERROR
queryFinal.getResultList();
Parameter value [[Ljava.lang.Object;@90d0bf] was not matching type [java.lang.Long]
I tried with or without (), I changed 开发者_JAVA技巧the version of Hibernate-Core to 3.6.4 (from JBoss 6.0.0.Final), otherwise if I wrote in :ids
without () I'd got an error.
Please Help.
The IN always worked, the problem was that List<Long> wasn't actually List<Long> was List<Object[]>. Thanks
I also use JBoss AS 6 and this exact construct, but it just works.
This is an example of a query:
<named-query name="Item.getByItemIDs">
<query>
SELECT
i
FROM
Item i
WHERE
i.ID in (:itemsIDs)
</query>
</named-query>
And of a class using it:
@Override
public List<Item> getByItemIDs(List<Long> itemIDs) {
return entityManager.createNamedQuery("Item.getByItemIDs", Item.class)
.setParameter("itemIDs", itemIDs)
.getResultList();
}
As your exception indicated [[Ljava.lang.Object;@90d0bf]
(which is an Object[]), maybe you should try List<Long> as in my example?
(p.s. You can use the fluid API of JPA to make your code a little less verbose)
The 'IN' clause in hibernate is very, very tricky, and as far as I remember doesn't play well with named parameters, but it does with positional parameters.
Try changing the query to this
@NamedQuery(name = "someName", query = "select x from X x where x.y.id in (?)")
and the code that uses it to
TypedQuery<X> query = getEntityManager().createNamedQuery("someName", X.class);
query.setParameter(1, someListOfLongs); // I can't remember if the position is 0 or 1 based.
queryFinal.getResultList();
And I should add that if the list is emtpy, you'll get an exception. In our code, we detect this situation and replace the empty list with a list that contains a '-1' and since all ids are positive we don't get any results back.
精彩评论