一 hql连接查询
和SQL查询一样,HQL也支持各种各样的连接查询,如内连接、外连接。我们知道在SQL中可通过join子句实现多表之间的连接查询。HQL同样提供了连接查询机制,还允许显式指定迫切内连接和迫切左外连接。HQL提供的连接方式如表1所示。
连接类型 | HQL语法 | 适用范围 |
内连接 | inner join或 join | 适用于有关联关系 |
迫切内连接 | inner join fetch或 join fetch | 的持久化类,并且在 |
左外连接 | left outer join或 left join | 映射文件中对这种关 |
迫切左外连接 | left outer join fetch或 left join fetch | 联关系做了映射 |
右外连接 | right outer join或 right join |
案例一,多对一关联,无迫切连接
package com.obtk.test2;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import com.obtk.entitys.DeptEntity;
import com.obtk.entitys.EmployeeEntity;
import com.obtk.utils.HibernateUtil;
public class TestJoin01 {
public static void main(String[] args) {
Session session=null;
String hql="from EmployeeEntity e inner join e.dept d " +
" where e.gender=? and d.deptName=? ";
try {
session=HibernateUtil.getSession();
Query qy=session.createQuery(hql);
qy.setParameter(0, "男");
qy.setParameter(1, "人事部");
List<Object[]> objList=qy.list();
EmployeeEntity theEmp=null;
DeptEntity dept=null;
for(Object[] theArr :objList){
theEmp=(EmployeeEntity)theArr[0];
dept=(DeptEntity)theArr[1];
System.out.println(theEmp.getEmpName()+","+theEmp.getGender()
+","+dept.getDeptName());
}
} catch (HibernateException e) {
e.printStackTrace();
}finally{
HibernateUtil.closeSession();
}
}
}
案例二 多对一关联,有迫切连接(注意fetch关键字)
package com.obtk.test2;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import com.obtk.entitys.DeptEntity;
import com.obtk.entitys.EmployeeEntity;
import com.obtk.utils.HibernateUtil;
public class TestFetchJoin01 {
public static void main(String[] args) {
Session session=null;
String hql="from EmployeeEntity e inner join fetch e.dept d " +
" where e.gender=? and d.deptName=? ";
try {
session=HibernateUtil.getSession();
Que