Query上有list()與iterate()方法,兩者的差別在於開啟Query快取之後,list()方法在讀取資料時,會利用到Query快取, 而iterate()則不會使用到Query快取功能,而是直接從資料庫中再查詢資料。
來看看下面的程式:
Session
session = sessionFactory.openSession();
Query query = session.createQuery("from User");
query.setCacheable(true);
List users = query.list();
users = query.list();
session.close();
Query query = session.createQuery("from User");
query.setCacheable(true);
List users = query.list();
users = query.list();
session.close();
這個程式片段會使用一次SQL來查詢資料庫,第二次直接從Query快取中取得資料:
Hibernate: select user0_.id as
id, user0_.name as name0_, user0_.age as age0_ from user user0_
使用iterate()方法時不會使用到Query快取,例如:
Session session =
sessionFactory.openSession();
Query query = session.createQuery("from User");
query.setCacheable(true);
Iterator users = query.iterate();
users = query.iterate();
session.close();
Query query = session.createQuery("from User");
query.setCacheable(true);
Iterator users = query.iterate();
users = query.iterate();
session.close();
這個程式片段會使用兩次SQL向資料庫查詢:
Hibernate: select user0_.id as
col_0_0_ from user user0_
Hibernate: select user0_.id as col_0_0_ from user user0_
Hibernate: select user0_.id as col_0_0_ from user user0_