首先看两个例子来比较一下
(1)在用Query方法查询的时候,通过HQL语句来得到Query对象,并对Query对象进行操作,首先是用list方法获取到Query的List集合并输出
public void listQuery() { Configuration configuration = new Configuration().configure(); SessionFactory factory = configuration.buildSessionFactory(); Session session = factory.openSession(); Query query = session.createQuery("fromCustomers"); List<Customers> list = query.list(); for(Customers entity:list){ System.out.println(entity.toString()); } }
输出的结果为:
List的执行sql语句为:
Hibernate: select customers0_.id as id0_, customers0_.realName as realName0_, customers0_.pass aspass0_, customers0_.sex
as sex0_, customers0_.petName as petName0_,customers0_.email as email0_, customers0_.rdate as rdate0_ from customerscustomers0_
[email protected]
(2)通过Query得到Query的对象,并用iterator迭代器输出
public void iterateQuery(){ Configuration configuration = new Configuration().configure(); SessionFactory factory = configuration.buildSessionFactory(); Session session = factory.openSession(); Query query = session.createQuery("from Customers"); Iterator<Customers> it = query.iterate(); // 遍历出来所有的查询结果 while (it.hasNext()) { Customers customer = it.next(); System.out.println(customer.toString()); } }
Iterator的执行结果:
Hibernate: select customers0_.id as col_0_0_ from customers customers0_
Hibernate: select customers0_.id as id0_0_, customers0_.realName as realName0_0_,customers0_.pass as pass0_0_, customers0_.sex
as sex0_0_, customers0_.petNameas petName0_0_, customers0_.email as email0_0_, customers0_.rdate as rdate0_0_from customers customers0_ where customers0_.id=?
[email protected]
分析:通过语句我们发现
- list()方法在执行时,直接运行查询结果所需要的查询语句。
- iterator()方法则是先执行得到对象ID的查询,然后在根据每个ID值去取得所要查询的对象
小结:
通过以上两者分析我们对比发现Query的两个方法,list()和
iterate(),两个方法都是把结果集列出来,他们有3点不一样,
- 返回的类型不一样,list()返回List,iterate()返回Iterator,
- 获取数据的方式不一样,list()会直接查数据库,iterate()会先到数据库中把id都取出来,然后真正要遍历某个对象的时候先到缓存中找,如果找不到,以id为条件再发一条sql到数据库,这样如果缓存中没有数据,则查询数据库的次数为n+1。
- iterate会查询2级缓存, list只会查询一级缓存。
- list()中返回的List中每个对象都是原本的对象,iterate()中返回的对象是代理对象.(debug可以发现)
总体的说来就是 一个为延迟加载,一个是直接查找数据源的问题。语言是不分界限的,就像NET中的Ienumerator与Iquery接口,说的也是这样的问题。