先执行list()后执行iterate(),结果如下:
结果:
------------list()方法-----------
Hibernate: select dept0_.DEPTNO as DEPTNO1_, dept0_.DNAME as DNAME1_, dept0_.LOC as LOC1_ from scott.dept dept0_
ACCOUNTING
RESEARCH
SALES
OPERATIONS
----------iterate()方法-----------
Hibernate: select dept0_.DEPTNO as col_0_0_ from scott.dept dept0_
ACCOUNTING
RESEARCH
SALES
OPERATIONS
先执行iterate()后执行list(),结果如下:
----------iterate()方法-----------
Hibernate: select dept0_.DEPTNO as col_0_0_ from scott.dept dept0_
Hibernate: select dept0_.DEPTNO as DEPTNO1_0_, dept0_.DNAME as DNAME1_0_, dept0_.LOC as LOC1_0_ from scott.dept dept0_ where dept0_.DEPTNO=?
ACCOUNTING
Hibernate: select dept0_.DEPTNO as DEPTNO1_0_, dept0_.DNAME as DNAME1_0_, dept0_.LOC as LOC1_0_ from scott.dept dept0_ where dept0_.DEPTNO=?
RESEARCH
Hibernate: select dept0_.DEPTNO as DEPTNO1_0_, dept0_.DNAME as DNAME1_0_, dept0_.LOC as LOC1_0_ from scott.dept dept0_ where dept0_.DEPTNO=?
SALES
Hibernate: select dept0_.DEPTNO as DEPTNO1_0_, dept0_.DNAME as DNAME1_0_, dept0_.LOC as LOC1_0_ from scott.dept dept0_ where dept0_.DEPTNO=?
OPERATIONS
------------list()方法-----------
Hibernate: select dept0_.DEPTNO as DEPTNO1_, dept0_.DNAME as DNAME1_, dept0_.LOC as LOC1_ from scott.dept dept0_
ACCOUNTING
RESEARCH
SALES
OPERATIONS
总结:
1、list()方法将不会再缓存中读取数据,它总是一次性的从数据库中直接查询所有符合条件的数据,同时将获取的数据写入缓存。
2、iterate()方法则是获取了符合条件的数据的ID后,首先根据ID在缓存中寻找符合条件的数据,若缓存中无符合条件的数据,再到数据库中查询
3、某些情况下,你可以使用 iterate() 方法得到更好的性能。 这通常是你预期返回的结果在 session,或二级缓存(second-level cache)
中已经存在时的情况。如若不然,iterate() 会比 list() 慢,而且可能简单查询也需要进行多次数据库访问:iterate() 会首先使用 1 条语句得到所有对象的持久化标识(identifiers),再根据持久化标识执行 n 条附加的 select 语句实例化实际的对象。