拥有此代码:
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
Query query = session.createQuery("from DBUser where id=1");
for(Iterator it=query.iterate();it.hasNext();){
Object[] row = (Object[]) it.next();
System.out.println("ID: " + row[0]);
System.out.println("Name: " + row[1]);
System.out.println("Amount: " + row[2]);
}
发生错误:java.lang.ClassCastException: com.mycompany.app.DBUser cannot be cast to [Ljava.lang.Object;
可能有更简单的方法从表中检索单个元素?
答案 0 :(得分:2)
hql返回映射类型。您的代码应如下所示:
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
Query query = session.createQuery("from DBUser where id=1");
for(Iterator it=query.iterate();it.hasNext();){
DBUser row = (DBUser) it.next();
System.out.println("ID: " + row.getId());
System.out.println("Name: " + row.getName());
System.out.println("Amount: " + row.getAmount());
}