我尝试使用以下代码将从Hibernate获得的列表转换为AdminPopulate类型,但出现此错误
线程“主”中的异常java.lang.ClassCastException:[Ljava.lang.Object;无法转换为模型。
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;
}
最佳答案
如果SubUser
类已正确映射到查询结果,则可以在执行查询之前调用query.addEntity(SubUser.class)
。
Query query = session.createSQLQuery(sql);
query.addEntity(SubUser.class);
resultsList = query.list();