一、HQL的一对多查询
班级(1)->(多)学生
/** * 实现Classes与Student的内连接 * * SELECT c.*,s.* * from classes c INNER JOIN student s * where (c.cid=s.cid) */ @Test public void testInnerJoin(){ session = HibernateUtils.openSession(); Query query = session.createQuery("from Classes c " + "inner join c.students s "); List list = query.list();//Object[] session.close(); } /** * 迫切内连接 */ @Test public void testInnerJoin_fetch(){ session = HibernateUtils.openSession(); Query query = session.createQuery("from Classes c " + "inner join fetch c.students s "); List list = query.list();//Classes session.close(); } /** * 左外连接 * SELECT c.*,s.* * from classes c LEFT OUTER JOIN student s * on(s.cid=c.cid) */ @Test public void testLeftOutJoin(){ session = HibernateUtils.openSession(); Query query = session.createQuery("from Classes c " + "left outer join c.students s "); List list = query.list();//Object[] session.close(); } /** * 迫切左外连接 * */ @Test public void testLeftOutJoin_fetch(){ session = HibernateUtils.openSession(); Query query = session.createQuery("from Classes c " + "left outer join fetch c.students s "); List list = query.list();//Classes session.close(); } /** * 要查询的属性来自两个持久化类 * 注意:带构造函数的查询不能 与 带fetch的查询同一时候存在 * 使用 fetch:是希望带Classes * */ @Test public void testQueryPropertyFromTwo(){ session = HibernateUtils.openSession(); List<ClassStuView> classStuViews = session.createQuery("select new cn.cil.domain.ClassStuView(c.name,s.name) " + " from Classes c inner join c.students s").list(); session.close(); }
二、HQL的多对多查询
学生(多)->(多)课程
/** * 迫切内连接 * */ @Test public void testInnerJoin_Fetch(){ Session session = sessionFactory.openSession(); session.createQuery("from Student s inner join fetch s.courses c").list(); session.close(); } /** * 迫切左外连接 */ @Test public void testLeftOuterJoin_Fetch(){ Session session = sessionFactory.openSession(); session.createQuery("from Student s left outer join fetch s.courses c").list(); session.close(); }
三、一对多与多对多结合
班级(1)->(多)学生->(多)课程
/** * 查询全部的班级的全部的学生的全部的课程 */ @Test public void testQuery1(){ Session session = HibernateUtils.openSession(); List<Classes> classes = session.createQuery("from Classes c inner join " + "fetch c.students s inner join " + "fetch s.courses cc").list(); session.close(); } @Test public void testQuery2(){ Session session = HibernateUtils.openSession(); List<Student> classes = session.createQuery("from Student s inner join fetch s.classes c inner join fetch s.courses cc").list(); session.close(); }
有用场景:
用户登录系统,推断该用户所拥有的权限。并进行显示权限范围内的菜单
依据username查用户依据用户查角色再依据角色查权限
createQuery("from Privilege p inner join fetch p.roles r inner join fetch r.users u where u.username=?")
当表与表之间的关系过于复杂的时候,就不能使用hibernate了,hql的书写会相当相当麻烦,能够採用视图来解决这一问题。使用JDBC拼SQL