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'

其他提示

If you look at the docs of Query#list() (emphasis mine)

Return the query results as a List. If the query contains multiple results pre row, the results are returned in an instance of Object[].

It returns a List of Object[], where each Object[] represents a row and when you try to cast this Object[] as a Session, you get the error,

java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to Session

Your query doesn't return a List<Session>, but a List<Object[]>, since it queries for two attributes (ID and NAME).

You shouldn't use SQL, but HQL. And your query should be

select s from Session s where s.deleted = false

(assuming your entity has a deleted field of type boolean).

You should also rename your entity to something other than Session, since it conflicts with the Hibernate Session type.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top