list 与iterate:
1 list是立刻查询 iterate使用延迟加载,有可能会产生n+1次查询
Session session=HibernateSessionFactory.getSession();
System.out.println("1:"+session);
session.beginTransaction();
Query query1=session.createQuery("from Books where id=7");
List<Books> list=query1.list();
/*System.out.println("2:"+session);
for(Books b:list){
System.out.println(b.getAuthor()+" "+b.getName());
}*/
Query query=session.createQuery("from Books where id<7");
Iterator<Books> books=query.iterate();
System.out.println("3:"+session);
while(books.hasNext()){
Books book=books.next();
book.getName();
}
session.getTransaction().commit();
HibernateSessionFactory.closeSession();
System.out.println("4:"+session);
2 list对1级缓存可写不可读
iterate对1级缓存可写可读
Session session=HibernateSessionFactory.getSession();
System.out.println("1:"+session);
session.beginTransaction();
Query query1=session.createQuery("from Books");
Iterator<Books> books=query1.iterate();
System.out.println("2:"+session);
while(books.hasNext()){
Books book=books.next();
book.getName();
System.out.println("3:"+session);
}
/*System.out.println("2:"+session);
for(Books b:list){
System.out.println(b.getAuthor()+" "+b.getName());
}*/
Query query=session.createQuery("from Books ");
Iterator<Books> books1=query.iterate();
System.out.println("3:"+session);
while(books1.hasNext()){
Books book=books1.next();
book.getName();
System.out.println("3:"+session);
}
session.getTransaction().commit();
HibernateSessionFactory.closeSession();
System.out.println("4:"+session);
}
get与load:
1 get是立刻加载 load是延迟加载,load的时候只是返回了一个proxy对象,
这个代理对象中只有id,没有其他数据,只有在触发必须查询点时才查询数据库
Session session=HibernateSessionFactory.getSession();
System.out.println("1:"+session);
session.beginTransaction();
Books b1=(Books)session.load(Books.class, 2);
b1.getName();
System.out.println("2:"+session);
Books b2=(Books)session.get(Books.class, 3);
System.out.println("3:"+session);
session.getTransaction().commit();
HibernateSessionFactory.closeSession();
System.out.println("4:"+session);
2 get假如获取不到具体数据,接着对对象进行操作,报空指针异常
load假如获取不到具体数据,报ObjectNotFoundException
Session session=HibernateSessionFactory.getSession();
System.out.println("1:"+session);
session.beginTransaction();
Books b1=(Books)session.load(Books.class, 2);
b1.getName();
System.out.println("2:"+session);
Books b2=(Books)session.get(Books.class, 3);
System.out.println("3:"+session);
session.getTransaction().commit();
HibernateSessionFactory.closeSession();
b2.getAuthor();
System.out.println("4:"+session);
}
3 get 对1级缓存可读可写
load对1级缓存可读可写
Session session=HibernateSessionFactory.getSession();
System.out.println("1:"+session);
session.beginTransaction();
Books b1=(Books)session.load(Books.class, 2);
b1.getName();
System.out.println("2:"+session);
Books b2=(Books)session.get(Books.class, 3);
System.out.println("3:"+session);
session.getTransaction().commit();
HibernateSessionFactory.closeSession();
b2.getAuthor();
System.out.println("4:"+session);
}