码迷,mamicode.com
首页 > Web开发 > 详细

hibernate中Query的list和iterator区别

时间:2016-07-09 16:29:03      阅读:168      评论:0      收藏:0      [点我收藏+]

标签:

1、Test_query_list类

public class Test_query_iterator_list {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml");
        SessionFactory sessionFactory=(SessionFactory) ac.getBean("sessionFactory");
        Session session=sessionFactory.openSession();        
        String hql="from User where id<=3";
        List<User> users=session.createQuery(hql).list();
        System.out.println("***************************************");
        for (User user: users) {
            System.out.println(user);
        }       
        session.close();       
    }

}

测试结果为:

Hibernate:
select
user0_.id as id0_,
user0_.name as name0_
from
mydb.user user0_
where
user0_.id<=3
***************************************
User [id=1, name=LI]
User [id=2, name=sara2]
User [id=3, name=sara3]

public class Test_query_iterator_list {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml");
        SessionFactory sessionFactory=(SessionFactory) ac.getBean("sessionFactory");
        Session session=sessionFactory.openSession();            
        String hql="from User where id<=3";
        Iterator<User> iterator=session.createQuery(hql).iterate();
        System.out.println("***************************************");
        while(iterator.hasNext()) {
            System.out.println(iterator.next());
        }        
        session.close();        
    }
}

输出结果为:

Hibernate:
select
user0_.id as col_0_0_
from
mydb.user user0_
where
user0_.id<=3
***************************************
Hibernate:
select
user0_.id as id0_0_,
user0_.name as name0_0_
from
mydb.user user0_
where
user0_.id=?
User [id=1, name=LI]
Hibernate:
select
user0_.id as id0_0_,
user0_.name as name0_0_
from
mydb.user user0_
where
user0_.id=?
User [id=2, name=sara2]
Hibernate:
select
user0_.id as id0_0_,
user0_.name as name0_0_
from
mydb.user user0_
where
user0_.id=?
User [id=3, name=sara3]

结论:

  可以看出list每次都是通过一条语句直接操作数据库取出所有的数据返回(并且将对象存入hibernate缓存);iterator首先通过一条语句取出所有数据的id,然后通过id在hibernate的一级缓存中查找是否存在该对象,如果存在则直接取出,如果没有则再次发出一条sql语句通过id取得对象(并且加入到缓存中),这样如果所有的id在缓存中都没有的话就会出现n+1条sql语句的问题。

hibernate中Query的list和iterator区别

标签:

原文地址:http://www.cnblogs.com/SaraMoring/p/5656030.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!