线程“main”中的异常java.lang.ClassCastException:[Ljava.lang.Object;无法转换为model.AdminPopulate

时间:2015-02-10 10:11:16

标签: java sql hibernate casting classcastexception

我尝试使用以下代码将我从Hibernate获取的List转换为AdminPopulate类型,我收到此错误

线程中的异常" main" java.lang.ClassCastException:[Ljava.lang.Object;无法转换为model.AdminPopulate

public class Test
{
public static void main(String[] args)
{
     SubUser subUser=new SubUser();        

     List subUserList=subUser.getSubUserAll();

     List<AdminPopulate> subUserListAdminPop=new ArrayList<AdminPopulate>();

     for(Object p:subUserList)
     {
         subUserListAdminPop.add((AdminPopulate)p);
     }         

     for(AdminPopulate p:subUserListAdminPop)
     {
         System.out.println("first ="+p.getFirstName());
     }
 }

}

....这是getSubUserAll()方法

 public List getSubUserAll()
{
    Session session=null;
    List resultsList=null;

    try
    {
       CreateHibernateSession hbSession=new CreateHibernateSession();

       session=hbSession.getHBSession();

       String sql = "SELECT SubUser.FirstName,\n" +
                    "SubUser.LastName,\n" +
                    "SubUser.UserName,\n" +
                    "SubUserType.Name\n" +
                    "FROM SubUser\n" +
                    "INNER JOIN SubUserType ON SubUser.idSubUserType = SubUserType.idSubUserType\n" +
                    "WHERE SubUserType.idSubUserType !=  0";

       Query query = session.createSQLQuery(sql);  

       resultsList = query.list(); 

       return resultsList;
    }
    catch(Exception ex)
    {
        ex.printStackTrace();
    }
    finally
    {
        session.close();
    }
    return resultsList;
}

2 个答案:

答案 0 :(得分:1)

如果SubUser类正确映射到查询结果,那么您可以在执行查询之前调用query.addEntity(SubUser.class)

Query query = session.createSQLQuery(sql);  
query.addEntity(SubUser.class);
resultsList = query.list(); 

答案 1 :(得分:0)

我不是Hibernate的专家,但你试图投射array of objects
(Object [] - &gt; [Ljava.lang.Object;),这意味着什么,方法{ {1}}已连续返回多个结果。如果你看一下你的SQL,很明显为什么,你在select中引用了两个表 我猜Query.list在每一行返回一个Object [2],其中第一个是SubUser,第二个元素是SubUserType。