标签:
一、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
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:
原文地址:http://blog.csdn.net/wjw0130/article/details/47700913