1.通过Session得到Query的对象,并用list集合输出
/**
* list: 1条查询语句
*/
@Test
public void list1() {
// 1)获得会话
Session session = HibernateUtil.currentSession();
// hql语句 Dept实体类
String hql = "from Dept";
// query对象
Query query = session.createQuery(hql);
// 返回List对象
List<Dept> list = query.list();
for (Dept dept : list) {
System.out.println(dept.getDeptno() + "\t" + dept.getDname() + "\t"
+ dept.getLoc());
}
}
执行的SQL语句:
Hibernate: select dept0_.DEPTNO as DEPTNO1_0_, dept0_.DNAME as DNAME2_0_, dept0_.LOC as LOC3_0_ from SCOTT.DEPT dept0_ 46 GO CC 41 TOO AA 42 GO CC 43 GO CC 10 ACCOUNTING NEW YORK 20 RESEARCH DALLAS 30 SALES CHICAGO 40 OPERATIONS BOSTON |
2.通过Session得到Query的对象,并用iterator迭代器输出
/*
*
* iterator N+1查询语句
*/
@Test
public void list2() {
// 1)获得会话
Session session = HibernateUtil.currentSession();
// hql语句 Dept实体类
String hql = "from Dept";
// query对象
Query query = session.createQuery(hql);
// 返回List对象
Iterator<Dept> it = query.iterate();
while (it.hasNext()) {
Dept dept = it.next();
System.out.println(dept.getDeptno() + "\t" + dept.getDname() + "\t"
+ dept.getLoc());
}
执行的SQL语句:
Hibernate: select dept0_.DEPTNO as col_0_0_ from SCOTT.DEPT dept0_ Hibernate: select dept0_.DEPTNO as DEPTNO1_0_0_, dept0_.DNAME as DNAME2_0_0_, dept0_.LOC as LOC3_0_0_ from SCOTT.DEPT dept0_ where dept0_.DEPTNO=? 10 ACCOUNTING NEW YORK Hibernate: select dept0_.DEPTNO as DEPTNO1_0_0_, dept0_.DNAME as DNAME2_0_0_, dept0_.LOC as LOC3_0_0_ from SCOTT.DEPT dept0_ where dept0_.DEPTNO=? 20 RESEARCH DALLAS Hibernate: select dept0_.DEPTNO as DEPTNO1_0_0_, dept0_.DNAME as DNAME2_0_0_, dept0_.LOC as LOC3_0_0_ from SCOTT.DEPT dept0_ where dept0_.DEPTNO=? 30 SALES CHICAGO Hibernate: select dept0_.DEPTNO as DEPTNO1_0_0_, dept0_.DNAME as DNAME2_0_0_, dept0_.LOC as LOC3_0_0_ from SCOTT.DEPT dept0_ where dept0_.DEPTNO=? 40 OPERATIONS BOSTON Hibernate: select dept0_.DEPTNO as DEPTNO1_0_0_, dept0_.DNAME as DNAME2_0_0_, dept0_.LOC as LOC3_0_0_ from SCOTT.DEPT dept0_ where dept0_.DEPTNO=? 41 TOO AA Hibernate: select dept0_.DEPTNO as DEPTNO1_0_0_, dept0_.DNAME as DNAME2_0_0_, dept0_.LOC as LOC3_0_0_ from SCOTT.DEPT dept0_ where dept0_.DEPTNO=? 42 GO CC Hibernate: select dept0_.DEPTNO as DEPTNO1_0_0_, dept0_.DNAME as DNAME2_0_0_, dept0_.LOC as LOC3_0_0_ from SCOTT.DEPT dept0_ where dept0_.DEPTNO=? 43 GO CC Hibernate: select dept0_.DEPTNO as DEPTNO1_0_0_, dept0_.DNAME as DNAME2_0_0_, dept0_.LOC as LOC3_0_0_ from SCOTT.DEPT dept0_ where dept0_.DEPTNO=? 46 GO CC |
总结:
(1)从上面的执行结果可以看出获取的方式不一样
List的获取方式为:List<Dept> list = query.list();
Iterator的获取方式:Iterator<Dept> it = query.iterate();
(2)从执行结果可以看出list输出一条语句,而iterator输出的是N+1条sql语句
因为他们获取数据的方式不一样,list()会直接查询数据库,iterator()会先到数据库中把id都取出来,然后真正要遍历某个对象的时候先到缓存中找,如果找不到,以id为条件再发一条sql到数据库,这样如果缓存中没有数据,则查询数据库的次数为n+1次
(3)list只查询一级缓存,而iterator会从二级缓存中查询.
(4)list方法返回的对象都是实体对象,而iterator返回的是代理对象.
(5) session中list第二次发出,仍会到数据库査询;而iterate 第二次,首先找session 级缓存.