package test;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import util.HibernateSessionFactory;
import entity.Student;
import entity.Teacher;
public class TestInnerJoin {
public static void main(String[] args) {
jion();// 内连接
leftJoin();// 左外连接
}
private static void jion() {
// 打开Session
Session session = HibernateSessionFactory.getSession();
// 内连接 hql 语句
String hql = "from Student s inner join s.teacher";
try {
// 实例查询对象
Query query = session.createQuery(hql);
// 获取列表
List<Object[]> lists = query.list();
// 遍历列表
for (Object[] list : lists) {
// 判断如果是 Student
if (list[0] instanceof Student) {
// 获取 Student 的列表
Student student = (Student) list[0];
System.out.print(student.getId() + " " + student.getName());
}
// 判断如果是 Teacher
if (list[1] instanceof Teacher) {
// 获取 Teacher 的列表
Teacher teacher = (Teacher) list[1];
System.out.println(teacher.getId() + " "
+ teacher.getName() + " ");
}
}
System.out.println("成功");
} catch (HibernateException e) {
e.printStackTrace();
} finally {
// 关闭 session,释放资源
HibernateSessionFactory.closeSession();
}
}
private static void leftJoin() {
// 打开Session
Session session = HibernateSessionFactory.getSession();
// 内连接 hql 语句
String hql = "from Student s left join s.teacher";
try {
// 实例查询对象
Query query = session.createQuery(hql);
// 获取列表
List<Object[]> lists = query.list();
// 遍历列表
for (Object[] list : lists) {
// 判断如果是 Student
if (list[0] instanceof Student) {
// 获取 Student 的列表
Student student = (Student) list[0];
System.out.print(student.getId() + " " + student.getName());
}
// 判断如果是 Teacher
if (list[1] instanceof Teacher) {
// 获取 Teacher 的列表
Teacher teacher = (Teacher) list[1];
System.out.println(teacher.getId() + " "
+ teacher.getName() + " ");
}
}
System.out.println("成功");
} catch (HibernateException e) {
e.printStackTrace();
} finally {
// 关闭 session,释放资源
HibernateSessionFactory.closeSession();
}
}
}
效果图: