首先看两个例子来比较一下
(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_
cn.csdn.products.domain.Customers@5bf624
(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=?
cn.csdn.products.domain.Customers@1d13272
分析:通过语句我们发现
通过以上两者分析我们对比发现Query的两个方法,list()和 iterate(),两个方法都是把结果集列出来,他们有3点不一样,
总体的说来就是 一个为延迟加载,一个是直接查找数据源的问题。语言是不分界限的,就像NET中的Ienumerator与Iquery接口,说的也是这样的问题。