simple question, but I don't see my error in reasoning. Having a named query with selected members as result instead of the entire row/entity.
Now I want to access the member fields with the convenient tuple methods.
q = em.createNamedQuery("test.findvar");
List<Tuple> tuples = q.getResultList();
for (Tuple t : tuples)
System.out.println(t.get(0) + " " + t.get(1));
Unfortunately it throws me:
Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to javax.persistence.Tuple
All works fine with:
q = em.createNamedQuery("test.findvar");
List<Object[]> objs = q.getResultList();
for (Object[] obj : objs)
System.out.println(obj[0] + " " + obj[1]);
What's wrong with my first solution?
You can specify return type in createNamedQuery(), as noted in javadoc
So your code should look like:
q = em.createNamedQuery("test.findvar", Tuple.class);
List<Tuple> tuples = q.getResultList();
for (Tuple t : tuples)
System.out.println(t.get(0) + " " + t.get(1));
When you specify return type, TypedQuery instance is created, instead of Query instance. Query does not use generics and returns simply java.util.List.