浅谈 Ljava.lang.Object 异常

    xiaoxiao2021-03-25  110

     初学者使用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();

    转载请注明原文地址: https://ju.6miu.com/read-9304.html

    最新回复(0)