List和iterator的區別

(1)在用Query方法查詢的時候,經過HQL語句來獲得Query對象,並對Query對象進行操做,首先是用list方法獲取到Query的List集合並輸出sql

public void listQuery() {數據庫

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

       SessionFactory factory = configuration.buildSessionFactory();session

       Session session = factory.openSession(); dom

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

       List<Customers> list = query.list();代理

       for(Customers entity:list){對象

           System.out.println(entity.toString());it

       }io

}

輸出的結果爲:

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<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_.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<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) session中list第二次發出,仍會到數據庫査詢

(6) iterate 第二次,首先找session 級緩存

相關文章
相關標籤/搜索