艺思网(www.edusrc.com)中国最大的中学教学资料下载网站
Hibernate 进行多表关联查询Hibernate对多个表进行查询时,查询结果是多个表的笛卡尔积,
或者称为“交叉”连接。 例如:from Student, Book from Student as stu, Book as boo from
Student stu, Book boo注意:让查询中的Student和Book均是表student和book对应的类名,它的
名字一定要和类的名字相同,包括字母的大小写。别名应该服从首字母小写的规则是一个好习惯,
这和Java对局部变量的命名规范是一致的。
例如:
String sTest = "from tBookInfo book, BookSelection sel where book.id = sel.bookId";
Collection result = new ArrayList();
Transaction tx = null;
try {
Session session = HibernateUtil.currentSession();
tx = session.beginTransaction();
Query query = session.createQuery(sql);
result = query.list();
tx.commit();
} catch (Exception e) {
throw e;
} finally {
HibernateUtil.closeSession();
}
ArrayList sList = (ArrayList) result;
Iterator iterator1 = sList.iterator();
while (iterator1.hasNext()) {
Object[] o = (Object[]) iterator1.next();
tBookInfo bookInfo = (tBookInfo) o[0];
BookSelection bookSelect = (BookSelection) o[1];
System.out.println("BookInfo-Title: " + bookInfo.getTitle());
System.out.println("BookSelection-BookSelectionId: " + bookSelect.getId());
}