1. 程式人生 > >Hibernate之HQL多表查詢

Hibernate之HQL多表查詢

多表的查詢進行使用HQL語句進行查詢,HQL語句和SQL語句的查詢語法比較類似

  • 內連線查詢
    • 顯示內連線
      • select * from customer c inner join orders o on c.cid = o.cno
    • 隱式內連線
      • select * from customers c.orders o where c.cid = o.cno;
  • 外連線查詢
    • 左連線查詢
      • select * from customers c left join orders o on c.cid = o.cno
    • 右連線查詢
      • select * from customer c right join orders o on c.cid = o.cno

    HQL 的多表查詢

    • 迫切和非迫切
      • 非迫切返回結果是Object[]
      • 迫切連線返回的結果是物件,把客戶的資訊封裝到客戶的物件中,把訂單資訊封裝到客戶的set集合中。

    內連線查詢

  • 內連線使用 inner join,預設返回的是Object陣列
Session session = HibernateUtils.getCurrentSession();
Transaction tr = session.beginTransaction();
List<Customer> list = session.beginTransaction();
Set<Customer> set = new HashSet<Customer>(list);
for(Customer customer:set){
	System.out.println(customer);
}
tr.commit();

迫切內連線 :inner join fetch,返回的是實體物件

Session session = HibernateUtils.getCurrentSession();
Transaction tr = session.beginTransaction();
List<Customer> list = session.createQuery("from Customer c inner join fetch c.linkmans").list();
Set<Customer> set = new HashSet<Customer>(list);//去掉重複
for(Customer customer : set){
	System.out.println(customer);
}
tr.commit;

左外連線查詢

左外連線:封裝成List<Object[]>

迫切左外連線

Session session = HIbernateUtils.getCurrentSession();
Transaction tr = session.beginTransaction();
List<Customer> list = session.createQuery("from Customer c left join fetch c.linkmans").list();
for(Customer customer : set){
	System.out.println(customer);
}
tr.commit();