十、Hibernate查詢之HQL多表查詢
阿新 • • 發佈:2018-12-05
關於HQL語句介紹使用可以檢視這裡,今天主要介紹其在多表系對映中的應用。
常用的sql語句多表查詢有以下幾種(以customers 和orders 表為例):
-
內連線查詢
- 顯示內連線
select * from customers 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 customers c right join orders o on c.cid = o.cno;
- 左外連線
多表的查詢中,HQL語句和SQL語句的查詢語法比較類似,HQL不用書寫select * 和on及後面的條件表示式,同時表名變成類名書寫,其他關鍵字不變.
HQL的多表查詢,根據返回結果劃分,可分為非迫切和迫切查詢,
- 非迫切:返回結果是List<Object[]>
- 迫切:返回結果是物件的集合,這個需要在join關鍵字後加上fetch關鍵字,同時需要手動解決資料重複的問題,可以通過set集合來解決
/**
* 非迫切內聯查詢:查詢的客戶及其聯絡人
* sql查詢:select * from cst_customer c,cst_linkman l where c.cust_id = l.lkm_cust_id;
* HQL查詢: from Customer c inner join c.linkmans
*/
@Test
public void test1() {
Session session = HibernateUtils.getCurrentSession();
Transaction tr = session.beginTransaction ();
Query query = session.createQuery("from Customer c inner join c.linkmans");
// 預設的返回值是陣列
List<Object[]> list = query.list();
for (Object[] objects : list) {
System.out.println(Arrays.toString(objects));
}
tr.commit();
}
/**
* 迫切內聯查詢:查詢的客戶及其聯絡人
* sql查詢:select * from cst_customer c,cst_linkman l where c.cust_id = l.lkm_cust_id;
* HQL查詢: from Customer c inner join fetch c.linkmans
*
* 使用fetch關鍵字,把資料封裝到物件中
*/
@Test
public void test2() {
Session session = HibernateUtils.getCurrentSession();
Transaction tr = session.beginTransaction();
Query query = session.createQuery("from Customer c inner join fetch c.linkmans");
// 預設返回的資料是沒有解決重複問題的
List<Customer> list = query.list();
for (Customer c : list) {
// System.out.println(c);
}
//手動解決資料重複的問題
Set<Customer> set = new HashSet<>(list);
for (Customer c : set) {
System.out.println(c);
}
tr.commit();
}
/**
* 迫切左外查詢:查詢的客戶及其聯絡人
* sql查詢:select * from cst_customer c left join cst_linkman l on c.cust_id = l.lkm_cust_id
* HQL查詢: from Customer c left join fetch c.linkmans
*
* 使用fetch關鍵字,把資料封裝到物件中
*/
@Test
public void test3() {
Session session = HibernateUtils.getCurrentSession();
Transaction tr = session.beginTransaction();
Query query = session.createQuery("from Customer c left join fetch c.linkmans");
//手動解決資料重複的問題
Set<Customer> set = new HashSet<>(query.list());
for (Customer c : set) {
System.out.println(c);
}
tr.commit();
}