使用隱式內連線查詢
阿新 • • 發佈:2018-11-15
package com.kgc.biz; import java.util.List; import org.hibernate.HibernateException; import org.hibernate.Query; import org.hibernate.Transaction; import com.kgc.common.HibernateSessionFactory; import com.kgc.dao.DeptDao; import com.kgc.po.Dept; import com.kgc.po.Emp; public class DeptBiz { private DeptDao dao = new DeptDao(); //查詢 public void findTest(){ Transaction tx = null; try { tx=HibernateSessionFactory.getSession().beginTransaction(); /**隱式連線查詢*/ String hql = " from Emp e where e.dept.dname= :dname"; Query query = HibernateSessionFactory.getSession().createQuery(hql); //查詢sales部門的員工 query.setParameter("dname", "SALES"); List<Emp> emps = query.list(); for(Emp e:emps){ System.out.println(e.getEname()+"\t"+e.getDept().getDname()); } tx.commit(); } catch (HibernateException e) { e.printStackTrace(); if(tx!=null){ tx.rollback(); } } } }
//測試類
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();
}
}
//執行結果
Hibernate: select emp0_.EMPNO as EMPNO0_, emp0_.ENAME as ENAME0_, emp0_.JOB as JOB0_, emp0_.MGR as MGR0_, emp0_.HIREDATE as HIREDATE0_, emp0_.SAL as SAL0_, emp0_.COMM as COMM0_, emp0_.DEPTNO as DEPTNO0_ from EMP emp0_, DEPT dept1_ where emp0_.DEPTNO=dept1_.DEPTNO and dept1_.DNAME=? Hibernate: select dept0_.DEPTNO as DEPTNO1_0_, dept0_.DNAME as DNAME1_0_, dept0_.LOC as LOC1_0_ from DEPT dept0_ where dept0_.DEPTNO=? -------------------------------------------------------- WARD SALES TURNER SALES ALLEN SALES JAMES SALES BLAKE SALES MARTIN SALES