注意: 是Query.iterate(),而不是Query.iterator();
Session session=HibernateSessionFactory.getSession();
List li=null;
Iterator it=null;
Date d=new Date();
System.out.print(d.toString());
Query q=session.createQuery("from TgovMaterialBak");
li=q.list();
li=q.list();
我们看输出:
Hibernate: select tgovmateri0_.SQLID as SQLID3_, tgovmateri0_.Id as Id3_, tgovmateri0_.CID as CID3_, tgovmateri0_.Addr as Addr3_, tgovmateri0_.Code as Code3_, tgovmateri0_.Code03 as Code6_3_, tgovmateri0_.Cname as Cname3_, tgovmateri0_.Name as Name3_, tgovmateri0_.Spec as Spec3_, tgovmateri0_.Unit as Unit3_, tgovmateri0_.PriceH as PriceH3_, tgovmateri0_.PriceM as PriceM3_, tgovmateri0_.PriceL as PriceL3_, tgovmateri0_.FID as FID3_, tgovmateri0_.FName as FName3_, tgovmateri0_.Brand as Brand3_, tgovmateri0_.Notes as Notes3_, tgovmateri0_.IssueDate as IssueDate3_, tgovmateri0_.EndDate as EndDate3_, tgovmateri0_.CreateON as CreateON3_, tgovmateri0_.CreateBy as CreateBy3_, tgovmateri0_.UpdateOn as UpdateOn3_, tgovmateri0_.UpdateBy as UpdateBy3_, tgovmateri0_.NodeIndex as NodeIndex3_, tgovmateri0_.DataID as DataID3_ from [Material-08].dbo.tGovMaterialBak tgovmateri0_
Hibernate: select tgovmateri0_.SQLID as SQLID3_, tgovmateri0_.Id as Id3_, tgovmateri0_.CID as CID3_, tgovmateri0_.Addr as Addr3_, tgovmateri0_.Code as Code3_, tgovmateri0_.Code03 as Code6_3_, tgovmateri0_.Cname as Cname3_, tgovmateri0_.Name as Name3_, tgovmateri0_.Spec as Spec3_, tgovmateri0_.Unit as Unit3_, tgovmateri0_.PriceH as PriceH3_, tgovmateri0_.PriceM as PriceM3_, tgovmateri0_.PriceL as PriceL3_, tgovmateri0_.FID as FID3_, tgovmateri0_.FName as FName3_, tgovmateri0_.Brand as Brand3_, tgovmateri0_.Notes as Notes3_, tgovmateri0_.IssueDate as IssueDate3_, tgovmateri0_.EndDate as EndDate3_, tgovmateri0_.CreateON as CreateON3_, tgovmateri0_.CreateBy as CreateBy3_, tgovmateri0_.UpdateOn as UpdateOn3_, tgovmateri0_.UpdateBy as UpdateBy3_, tgovmateri0_.NodeIndex as NodeIndex3_, tgovmateri0_.DataID as DataID3_ from [Material-08].dbo.tGovMaterialBak tgovmateri0_
系统等于执行了两次select * from tGovMaterialBak
我们再看看:
Session session=HibernateSessionFactory.getSession();
List li=null;
Iterator it=null;
Date d=new Date();
System.out.print(d.toString());
Query q=session.createQuery("from TgovMaterialBak");
it=q.iterate();
it=q.iterate();
Hibernate: select tgovmateri0_.SQLID as col_0_0_ from [Material-08].dbo.tGovMaterialBak tgovmateri0_
Hibernate: select tgovmateri0_.SQLID as col_0_0_ from [Material-08].dbo.tGovMaterialBak tgovmateri0_
从输出语句我们可以知道,系统只是执行了两次select id from TgovMaterialBak ,这就是为什么在海量数据时用list()会导致超出内存,而iterate()可以快速返回的原因了,这里也折射了一个SQL优化原则,在不用select *的地方就尽量不要用select *!