如果我们在Hibernate中需要查询多个表的不同字段,如何来获取结果呢?
有两种方式:
1、 对各个字段分别转化成对应类型,如下:
Java代码
- Query q = session.createQuery(" select members, classInfo.className " +
- " from Members members, ClassInfo classInfo " +
- " where members.level = classInfo.classCode ");
-
- List result = q.list();
- Iterator it = result.iterator();
- while (it.hasNext()) {
- Object[] tuple = (Object[]) it.next();
- Members members = (Members) tuple[ 0 ];
- String className = (String) tuple[ 1 ];
- }
2、构造自己的复合类型,如下:
Java代码
- Query q = session.createQuery(" select new NewMembers(members, classInfo.className) " +
- " from Members members, ClassInfo classInfo " +
- " where members.level = classInfo.classCode ");
当然我们需要有一个NewMembers类和相应的构造方法。