浅谈 [Ljava.lang.Object 异常

来源:互联网 发布:python splite 编辑:程序博客网 时间:2024/06/05 04:11

初学者使用hibernate执行查询的时候,很容易遇到结果集的类型转换问题,所以明确“执行结果”里的数据类型很重要。下面有两小例子:

(1):使用HQL进行条件查询。此结果集List包含的是对象数组,其中对象数组的索引0位置是Dept对象,该对象数组的长度取决于参与的表的个数。

 

 

    Session session = HibernateSessionFactory.getSession();

 

Query q = session.createQuery("from Dept d where d.dept is not null");

List<Object> list = query.list();//List包含的是对象数组

for(int i = 0 ; i < list.size(); i ++){//循环打印Dept的属性值

Object [] obj = (Object [])list.get(i);//obj中保存的是查询出的对象

Dept d = (Dept)obj[0];//索引0位置是Dept对象

System.out.println(d.getDname() );

}

 

    HibernateSessionFactory.closeSession();

(2):使用SQL进行条件查询。此结果集List包含的也是对象数组,不同的是对象数组索引0位置是Dept对象的第一个属性,该对象数组的长度取决于Dept表的属性的多少。

    Session session = HibernateSessionFactory.getSession();

 

Query q = session.createSQLQuery("select * from DEPT where FatherNo is not null"); 

List<Object> list = q.list();

for(int i=0;i<list.size();i++){

Object[] obj = (Object[])list.get(i);//obj中保存的是查询出的对象的属性值

for(int j = 0 ; j < obj.length; j ++){//循环打印Dept的属性值

System.out.print(obj[j] + "/t");

}

System.out.println("/n");

}

 

    HibernateSessionFactory.closeSession();

 

 

 

原创粉丝点击