使用隐式内连接查询

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

猜你喜欢

转载自blog.csdn.net/kimi_n/article/details/83957797