【HQL】分页查询 、对象导航查询、外置命名查询、连接查询、查询过滤器、统计查询
分页查询
List students = session.createQuery("from Student") .setFirstResult(1) .setMaxResults(2) .list(); for (Iterator iter=students.iterator(); iter.hasNext();) { Student student = (Student)iter.next(); System.out.println(student.getName()); }
对象导航查询
session = HibernateUtils.getSession(); session.beginTransaction(); List students = session.createQuery("from Student s where s.classes.name like '%2%'") .list(); for (Iterator iter=students.iterator(); iter.hasNext();) { Student student = (Student)iter.next(); System.out.println(student.getName()); }
外置命名查询
List students = session.getNamedQuery("queryStudent") .setParameter(0, 10) .list(); for (Iterator iter=students.iterator(); iter.hasNext();) { Student student = (Student)iter.next(); System.out.println(student.getName()); }
连接查询
List students = session.createQuery("select c.name, s.name from Student s join s.classes c") .list(); for (Iterator iter=students.iterator(); iter.hasNext();) { Object[] obj = (Object[])iter.next(); System.out.println(obj[0] + ", " + obj[1]); }
List students = session.createQuery("select c.name, s.name from Student s left join s.classes c") .list(); for (Iterator iter=students.iterator(); iter.hasNext();) { Object[] obj = (Object[])iter.next(); System.out.println(obj[0] + ", " + obj[1]); }
List students = session.createQuery("select c.name, s.name from Student s right join s.classes c") .list(); for (Iterator iter=students.iterator(); iter.hasNext();) { Object[] obj = (Object[])iter.next(); System.out.println(obj[0] + ", " + obj[1]); }
查询过滤器
session.enableFilter("testFilter") .setParameter("myid", 10); List students = session.createQuery("from Student").list(); for (Iterator iter=students.iterator(); iter.hasNext();) { Student student = (Student)iter.next(); System.out.println(student.getName()); }
统计查询
List list = session.createQuery("select count(*) from Student").list(); // Long count = (Long)list.get(0); Long count = (Long)session.createQuery("select count(*) from Student").uniqueResult(); // Long count = (Long)session.createQuery("select count(*) from Student") // .setMaxResults(1) // .uniqueResult(); System.out.println("count=" + count);
String hql = "select c.name, count(s) from Classes c join c.students s group by c.name order by c.name"; List students = session.createQuery(hql).list(); for (int i=0; i<students.size(); i++) { Object[] obj = (Object[])students.get(i); System.out.println(obj[0] + ", " + obj[1]); }