电脑技术学习

Hibernate对多个表进行关联查询实例

dn001

  下面列举一个完整的例子来说明Hibernate对多个表进行关联查询(其中粗体是我们要特别注意的地方,相应表tBookInfo和BookSelection的结构和其对应的hbm.xml、class文件就不一一列举了,有需要详细了解的朋友,请联系我):

  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());

  }

标签: 查询