list 和 iterate 不同之处
a) list取所有;
b) iterate 先取ID,等到用到的时候再根据ID来取对象;
c) session 中 list 第二次发出,仍会到数据库查询;
d) iterate 第二次,首先找 session 级缓存。
测试1:
@Test
public void testQueryList(){
Session session = sf.getCurrentSession();
session.beginTransaction(); List<Category> li = (List<Category>)session.createQuery("from Category").list(); for(Category c : li){
System.out.println(c.getId() + "-" + c.getName() );
} List<Category> li2 = (List<Category>)session.createQuery("from Category").list();
for(Category c : li2){
System.out.println(c.getId() + "-" + c.getName() );
} session.getTransaction().commit();
}
测试2:
@Test
public void testQueryIterate(){
Session session = sf.getCurrentSession();
session.beginTransaction(); Iterator<Category> it = (Iterator<Category>)session.createQuery("from Category c where c.id < 4").iterate(); while(it.hasNext()){
Category c = it.next();
System.out.println(c.getId() + "-" + c.getName());
} Iterator<Category> it2 = (Iterator<Category>)session.createQuery("from Category c where c.id < 4").iterate();
while(it2.hasNext()){
Category c = it2.next();
System.out.println(c.getId() + "-" + c.getName());
}
session.getTransaction().commit();
}
执行结果: