List和iterator
List 会直接全部选取到session并且再一次请求依然会发sql语句,而不会从session级缓存获取
测试如下:
@org.junit.Test
public void testList(){
session.beginTransaction();
List list=session.createQuery("from Person").list();
for(int i=0;i
Person p=(Person)list.get(i);
System.out.println(p.getName());
}
List list2=session.createQuery("from Person").list();
for(int i=0;i
Person p=(Person)list2.get(i);
System.out.println(p.getName());
}
session.getTransaction().commit();
}
结果:Hibernate:
select
person0_.id as id0_,
person0_.name as name0_
from
Person person0_
zhangqi_0
zhangqi_1
zhangqi_2
Hibernate:
select
person0_.id as id0_,
person0_.name as name0_
from
Person person0_
zhangqi_0
zhangqi_1
zhangqi_2
zhangqi_9
iterator则首先将所有id加载到session级内存,然后再逐条根据id发sql。
若再次请求,则直接从session获取,而不会发sql语句
代码:
@org.junit.Test
public void testIterator(){
session.beginTransaction();
Iterator it=session.createQuery("from Person").iterate();
while(it.hasNext()){
Person p=(Person)it.next();
System.out.println(p.getName());
}
Iterator it2=session.createQuery("from Person").iterate();
while(it2.hasNext()){
Person p=(Person)it2.next();
System.out.println(p.getName());
}
session.getTransaction().commit();
}
结果:
Hibernate:
select
person0_.id as col_0_0_
from
Person person0_
Hibernate:
select
person0_.id as id0_0_,
person0_.name as name0_0_
from
Person person0_
where
person0_.id=?
zhangqi_0
Hibernate:
select
person0_.id as id0_0_,
person0_.name as name0_0_
from
Person person0_
where
person0_.id=?
zhangqi_1
Hibernate:
select
person0_.id as id0_0_,
person0_.name as name0_0_
from
Person person0_
where
person0_.id=?
zhangqi_2
Hibernate:
select
person0_.id as id0_0_,
person0_.name as name0_0_
from
Person person0_
where
person0_.id=?
zhangqi_3
zhangqi_0
zhangqi_1
zhangqi_2