I wrote this code to cast an iterator object to a predefined object but it fails and it raise a class cast exception:
public ArrayList<Session> getAllSessions() {
ArrayList<Session> sessions = new ArrayList<Session>();
Query sessionsQuery = null;
sessionsQuery = this.getSession().getNamedQuery("getAllSessions");
Iterator trainees = sessionsQuery.list().iterator();
while (trainees.hasNext()) {
sessions.add((Session) trainees.next());
}
return sessions;
}
java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to Session
Query:
<sql-query name="getAllSessions"><![CDATA[ select ss.ID,ss.NAME from SESSION_ ss where ss.ISDELETED<>1]]></sql-query>
what is the problem here?
Best solution for your problem and probably will reduce your code is
return sessionsQuery.list();
In above problem you are iterating list using iterator and again storing into an ArrayList unnecesarry creating an object
Instead return that list what you are getting from above code.
After seeing your name Query, I found out that it will give you
List<Object[]>
because you have passed projections for select operator
Instead you can make your query as
Select sess from SESSION sess where 'your condition what you want'