取查询结果的几种方法

List:
A. 查询语句中只查一个字段
       
引用
Session session = HibernateSessionFactory.currentSession();
        Transaction transaction = session.beginTransaction();
        Query query = session.createQuery( "select e.name from Employee e");
        List list = query.list();
        for (int i = 0; i < list.size(); i++) {
            Object object = (Object)list.get(i);
            String s = (String) object;
            System.out.println(s);
        }

B. 查询语句中多于一个字段
    
引用
Session session = HibernateSessionFactory.currentSession();
        Transaction transaction = session.beginTransaction();
        Query query = session.createQuery( "select d.name, e.name from Department d, Employee e where d.id=e.department.id");
        List list = query.list();
        for (int i = 0; i < list.size(); i++) {
            Object[] object = (Object[])list.get(i);
            String s = (String) object[0];
            System.out.println(s);           
        }


Iterator:
也看查询语句中的字段,
A 如果是查整个表,可以直接转换为对象。
    
引用
HQL: from Department
        for (Iterator iter = query.iterate(); iter.hasNext(); ) {
            Department department = (Department) iter.next();
            System.out.println(department.getName());
        }

B 如果字段为一个,直接用实际的字段类型转换。
    
引用
HQL: select e.name from Employee e
        for (Iterator iter = query.iterate(); iter.hasNext(); ) {
            String s = (String) iter.next();
            System.out.println(s);
        }

C 如果字段多于一个,先用Object[]取出,然后陆续用实际字段的名字转换。
    
引用
HQL: select d.name, e.name from Department d, Employee e where d.id=e.department.id
       for (Iterator iter = query.iterate(); iter.hasNext(); ) {
            Object[] object (Object[]) inter.next();
            String s = (String) object[0];
            System.out.println(s);
        }

你可能感兴趣的:(C++,c,C#)