和SQL查询一样,HQL也支持各种各样的连接查询,如内连接、外连接。我们知道在SQL中可通过join字句实现多表之间的连接查询。HQL同样提供了连接查询机制,还允许显示指定迫切内连接和迫切左外连接。HQL提供的连接方式如下表所示。
//迫切内连接查询
@Test
public void test1() {
Query query = session.createQuery("select distinct s from Pro s inner join fetch s.emps");
List<Pro> list = query.list();
for (Pro item : list
) {
System.out.println(item.getProname());
for (Emp itme1 : item.getEmps()
) {
System.out.println(itme1.getEmpname());
}
}
}
//左外链接
@Test
public void test2() {
Query query = session.createQuery("select distinct s from Pro s left outer join s.emps");
List<Pro> list = query.list();
for (Pro item : list
) {
System.out.println(item.getProname());
for (Emp itme1 : item.getEmps()
) {
System.out.println(itme1.getEmpname());
}
}
}
//迫切左外链接
@Test
public void test3() {
Query query = session.createQuery("select distinct s from Pro s left outer join fetch s.emps");
List<Pro> list = query.list();
for (Pro item : list
) {
System.out.println(item.getProname());
for (Emp itme1 : item.getEmps()
) {
System.out.println(itme1.getEmpname());
}
}
}
//右链接
@Test
public void test4() {
Query query = session.createQuery("select distinct s from Pro s right join s.emps");
List<Pro> list = query.list();
for (Pro item : list
) {
System.out.println(item.getProname());
for (Emp itme1 : item.getEmps()
) {
System.out.println(itme1.getEmpname());
}
}
}