简体   繁体   English

无法转换迭代器对象

[英]Can not cast iterator object

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 在上面的问题中,您正在使用迭代器迭代列表,然后再次将其不必要地存储到ArrayList中以创建对象

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) 如果您查看Query#list()的文档(重点是我的)

Return the query results as a List. 以列表形式返回查询结果。 If the query contains multiple results pre row, the results are returned in an instance of Object[] . 如果查询在行前包含多个结果,则结果将在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, 它返回一个Object[]列表,其中每个Object[]代表一行,当您尝试将此Object[]强制转换为Session ,会收到错误消息,

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 ). 您的查询不会返回List<Session> ,而是返回List<Object[]> ,因为它查询两个属性( IDNAME )。

You shouldn't use SQL, but HQL. 您不应该使用SQL,而应使用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). (假设您的实体具有boolean类型的已deleted字段)。

You should also rename your entity to something other than Session, since it conflicts with the Hibernate Session type. 您还应该将实体重命名为Session以外的名称,因为它与Hibernate Session类型冲突。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM