1.*list是立刻加载:
package com.test;
import java.util.Iterator;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import com.factory.HibernateSessionFactory;
import com.pojo.Books;
public class Test4 {
/**
* @param args
*/
public static void main(String[] args) {
Session session=HibernateSessionFactory.getSession();
System.out.println("1: "+session);
session.beginTransaction();
Query query=session.createQuery("from Books where id<?");
query.setInteger(0, 3);
List<Books> list=query.list();
for(Books b:list){
System.out.println(b.getId()+"\t"+b.getName()+"\t"+b.getAuthor()+
"\t"+b.getPrice());
}
session.getTransaction().commit();
HibernateSessionFactory.closeSession();
System.out.println("4: "+session);
}
}
此次查询会产生一条sql语句:
Hibernate:
select
books0_.id as id0_,
books0_.name as name0_,
books0_.price as price0_,
books0_.opendate as opendate0_,
books0_.enddate as enddate0_,
books0_.author as author0_
from
test.books books0_
where
books0_.id<?
执行list之后的session中已放入数据:
SessionImpl(PersistenceContext[entityKeys=[EntityKey[com.pojo.Books#2], EntityKey[com.pojo.Books#1]],collectionKeys=[]];ActionQueue[insertions=[] updates=[] deletions=[] collectionCreations=[] collectionRemovals=[] collectionUpdates=[]])
*iterate是延迟加载:
iterate只查询出数据表中的所有主键id列表,当需要该对象其他数据时才会根据主键去数据库中查询
执行以上代码会产生n+1条sql语句:package com.test; import java.util.Iterator; import java.util.List; import org.hibernate.Query; import org.hibernate.Session; import com.factory.HibernateSessionFactory; import com.pojo.Books; public class Test4 { /** * @param args */ public static void main(String[] args) { Session session=HibernateSessionFactory.getSession(); System.out.println("1: "+session); session.beginTransaction();
Query query2=session.createQuery("from Books where id=?"); query2.setInteger(0, 5); Iterator<Books> books=query2.iterate(); while(books.hasNext()){ Books book=books.next(); System.out.println(book.getName()); } System.out.println("2: "+session); session.getTransaction().commit(); HibernateSessionFactory.closeSession(); } }
Hibernate:
select
books0_.id as col_0_0_
from
test.books books0_
where
books0_.id=?
Hibernate:
select
books0_.id as id0_0_,
books0_.name as name0_0_,
books0_.price as price0_0_,
books0_.opendate as opendate0_0_,
books0_.enddate as enddate0_0_,
books0_.author as author0_0_
from
test.books books0_
where
books0_.id=?
2. list对一级缓存是可写不可读:
Query query=session.createQuery("from Books where id<?");
query.setInteger(0, 3);
List<Books> list=query.list();
for(Books b:list){
System.out.println(b.getId()+"\t"+b.getName()+"\t"+b.getAuthor()+"\t"+b.getPrice());
}
Query query2=session.createQuery("from Books where id<?");
query2.setInteger(0, 3);
List<Books> list2=query2.list();
for(Books b:list2){
System.out.println(b.getId()+"\t"+b.getName()+"\t"+b.getAuthor()+"\t"+b.getPrice());
}
虽然查询条件一样,但是每使用一次list就会查询一次数据库
iterate对1级缓存可写也可读:
缓存中只有主键列表