Hibernate面试题 --- list和iterator方法的区别
1.首先看两个例子来比较一下
(1)在用Query方法查询的时候,通过HQL语句来得到Query对象,并对Query对象进行操作,首先是用list方法获取到Query的List集合并输出:
1 @Test 2 public void listQuery() { 3 4 Configuration configuration = new Configuration().configure(); 5 SessionFactory factory = configuration.buildSessionFactory(); 6 Session session = factory.openSession(); 7 Query query = session.createQuery("from Customers"); 8 List<Customers> list = query.list(); 9 10 for(Customers entity:list){ 11 System.out.println(entity.toString()); 12 } 13 }
List的执行sql语句为
1 Hibernate: select customers0_.id as id0_, customers0_.realName as realName0_, customers0_.pass as pass0_, customers0_.sex as sex0_, customers0_.petName as petName0_, customers0_.email as email0_, customers0_.rdate as rdate0_ from customers customers0_cn.csdn.products.domain.Customers@5bf624
(2)通过Query得到Query的对象,并用iterator迭代器输出
1 (2)通过Query得到Query的对象,并用iterator迭代器输出 2 3 public void iterateQuery(){ 4 5 Configuration configuration = new Configuration().configure(); 6 SessionFactory factory = configuration.buildSessionFactory(); 7 Session session = factory.openSession(); 8 Query query = session.createQuery("from Customers"); 9 Iterator<Customers> it = query.iterate(); 10 11 // 遍历出来所有的查询结果 12 while (it.hasNext()) { 13 Customers customer = it.next(); 14 System.out.println(customer.toString()); 15 } 16 }
Iterator的执行结果:
1 Hibernate: select customers0_.id as col_0_0_ from customers customers0_ 2 3 Hibernate: select customers0_.id as id0_0_, customers0_.realName as realName0_0_, customers0_.pass as pass0_0_, customers0_.sex as sex0_0_, customers0_.petName as petName0_0_, customers0_.email as email0_0_, customers0_.rdate as rdate0_0_ from customers customers0_ where customers0_.id=? 4 5 cn.csdn.products.domain.Customers@1d13272
结论:
(1)从上面的执行结果可以看出获取的方式不一样
List的获取方式为:List<Customers> list = query.list();
Iterator的获取方式:Iterator<Customers> it = query.iterate();
(2)从执行结果可以看出list输出一条语句,而iterator输出的是两条sql语句,我们可想一下,为什么会输出这样的效果?
因为他们获取数据的方式不一样,list()会直接查询数据库,iterator()会先到数据库中把id都取出来,然后真正要遍历某个对象的时候先到缓存中找,如果找不到,以id为条件再发一条sql到数据库,这样如果缓存中没有数据,则查询数据库的次数为n+1次
(3)list只查询一级缓存,而iterator会从二级缓存中查
(4)list方法返回的对象都是实体对象,而iterator返回的是代理对象
(5)list, iterator在hibernate中的区别之处, 此处iterator会出现1+N问题而list则不会
时间: 2024-10-11 23:53:46