Hibernate面试题 --- list和iterator方法的区别

 

Hibernate面试题  ---  list和iterator方法的区别

1.首先看两个例子来比较一下

(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("from Customers");

       List 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 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迭代器输出

    public void iterateQuery(){

       Configuration configuration = new Configuration().configure();

       SessionFactory factory = configuration.buildSessionFactory();

       Session session = factory.openSession();

       Query query = session.createQuery("from Customers");

       Iterator 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_.petName as petName0_0_, customers0_.email as email0_0_, customers0_.rdate as rdate0_0_ from customers customers0_ where customers0_.id=?

cn.csdn.products.domain.Customers@1d13272

 

结论:

(1)       从上面的执行结果可以看出获取的方式不一样

List的获取方式为:

                           List list = query.list();

      Iterator的获取方式:

           Iterator it = query.iterate();

(2)从执行结果可以看出list输出一条语句,而iterator输出的是两条sql语句,我们可想一下,为什么会输出这样的效果?

因为他们获取数据的方式不一样,list()会直接查询数据库,iterator()会先到数据库中把id都取出来,然后真正要遍历某个对象的时候先到缓存中找,如果找不到,以id为条件再发一条sql到数据库,这样如果缓存中没有数据,则查询数据库的次数为n+1次

(3)list只查询一级缓存,而iterator会从二级缓存中查

(4)list方法返回的对象都是实体对象,而iterator返回的是代理对象

        

        

        

你可能感兴趣的:(Hibernate面试题 --- list和iterator方法的区别)