hibernate 迫切左外連線
阿新 • • 發佈:2018-11-11
非迫切:返回list中每部分是陣列(不牽手)
迫切:返回list每部分是物件(牽手,只需將左表放入集合中)
//dept業務層
package com.kgc.biz; import java.util.List; import org.hibernate.HibernateException; import org.hibernate.Transaction; import com.kgc.common.HibernateSessionFactory; import com.kgc.dao.DeptDao; import com.kgc.po.Dept; public class DeptBiz { private DeptDao dao = new DeptDao(); //查詢 public void findTest(){ Transaction tx = null; try { tx=HibernateSessionFactory.getSession().beginTransaction(); String hql = "from Dept d left join fetch d.emps"; List<Dept> result = dao.find(hql); for (Dept dept : result) { System.out.println(dept); } tx.commit(); } catch (HibernateException e) { e.printStackTrace(); if(tx!=null){ tx.rollback(); } } } }
//test
package com.kgc.test;
import com.kgc.biz.DeptBiz;
import com.kgc.biz.EmpBiz;
import com.kgc.po.Dept;
import com.kgc.po.Emp;
public class DeptTest {
public static void main(String[] args) {
DeptBiz biz = new DeptBiz();
biz.findTest();
}
}
//執行結果
select
dept0_.DEPTNO as DEPTNO1_0_,
emps1_.EMPNO as EMPNO0_1_,
dept0_.DNAME as DNAME1_0_,
dept0_.LOC as LOC1_0_,
emps1_.ENAME as ENAME0_1_,
emps1_.JOB as JOB0_1_,
emps1_.MGR as MGR0_1_,
emps1_.HIREDATE as HIREDATE0_1_,
emps1_.SAL as SAL0_1_,
emps1_.COMM as COMM0_1_,
emps1_.DEPTNO as DEPTNO0_1_,
emps1_.DEPTNO as DEPTNO1_0__,
emps1_.EMPNO as EMPNO0__
from
DEPT dept0_
left outer join
EMP emps1_
on dept0_.DEPTNO=emps1_.DEPTNO
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
--------------------------------------------------列印部門id name size----------------------------------------------------------------------------
for (Dept dept : result) {
System.out.println(dept.getDeptno()+"\t"+dept.getDname()+"\t"+dept.getEmps().size());
}
-----------------執行結果--------------------
10 ACCOUNTING 3
10 ACCOUNTING 3
10 ACCOUNTING 3
20 RESEARCH 5
20 RESEARCH 5
20 RESEARCH 5
20 RESEARCH 5
20 RESEARCH 5
30 SALES 6
30 SALES 6
30 SALES 6
30 SALES 6
30 SALES 6
30 SALES 6
40 OPERATIONS 0