如果我们在Hibernate中需要查询多个表的不同字段,那么如何来获取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 ];
- }
- 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 ]; }
这是获取Hibernate多表查询的结果的最常用的方式。
2、构造自己的复合类型,如下:
Java代码:
- Query q = session.createQuery
- (" select new NewMembers(members, classInfo.className) " +
- " from Members members, ClassInfo classInfo " +
- " where members.level = classInfo.classCode ");
- Query q = session.createQuery
- (" select new NewMembers(members, classInfo.className)
- " + " from Members members, ClassInfo classInfo " + "
- where members.level = classInfo.classCode ");
当然我们需要有一个NewMembers类和相应的构造方式。以上便是两种用于获取Hibernate多表查询的结果的方法以及其相应的代码。
【编辑推荐】