取查询结果的几种方法

List:
A. 查询语句中只查一个字段
[quote]Session session = HibernateSessionFactory.currentSession();
Transaction transaction = session.beginTransaction();
Query query = session.createQuery([color=blue]"select e.name from Employee e"[/color]);
List list = query.list();
for (int i = 0; i < list.size(); i++) {
[color=blue]Object object = (Object)list.get(i);[/color]
String s = (String) object;
System.out.println(s);
}[/quote]
B. 查询语句中多于一个字段
[quote]Session session = HibernateSessionFactory.currentSession();
Transaction transaction = session.beginTransaction();
Query query = session.createQuery([color=blue]"select d.name, e.name from Department d, Employee e where d.id=e.department.id"[/color]);
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);
}[/quote]

Iterator:
也看查询语句中的字段,
A 如果是查整个表,可以直接转换为对象。
[quote]HQL: from Department
for (Iterator iter = query.iterate(); iter.hasNext(); ) {
Department department = (Department) iter.next();
System.out.println(department.getName());
}[/quote]
B 如果字段为一个,直接用实际的字段类型转换。
[quote]HQL: select e.name from Employee e
for (Iterator iter = query.iterate(); iter.hasNext(); ) {
String s = (String) iter.next();
System.out.println(s);
}[/quote]
C 如果字段多于一个,先用Object[]取出,然后陆续用实际字段的名字转换。
[quote]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);
}[/quote]

你可能感兴趣的:(Hibernate)