在hibernate.cfg.xml加上
<property name="hibernate.cache.use_query_cache">true</property> //注意不是name="hibernate.use_query_cache" 也不是name="cache.use_query_cache" 千万小心, //要不然,不成功,但也不报错,这是教训
注:1.查询缓存是sessionFactory级别的
2.查询缓存可以对属性,也可以对整个对象(看成是所有属性)
3 查询缓存对完全相同的HQL或sql有效
java代码:
A) 对属性缓存:
session = HibernateUtils.getSession();
tx = session.beginTransaction();
Query q=session.createQuery("select e.name from Employee e");
q.setCacheable(true);
List<Object> list =q
//.addScalar("id", StandardBasicTypes.INTEGER).
//.addScalar("name", StandardBasicTypes.STRING)
//.setCacheRegion("myCacheRegion")
.list();
for (int i = 0; list != null && i < list.size(); i++) {
Object obj = list.get(i);
System.out.println(((String)obj));
}
tx.commit();
session = HibernateUtils.getSession(); //就算新开事务,也可以缓存
tx=session.beginTransaction();
Query q2=session.createQuery("select e.name from Employee e");
q2.setCacheable(true); //注意这是query的设置,也即查询缓存,而不是session缓存
List<Object> list2 = q2
//.addScalar("id", StandardBasicTypes.INTEGER).
//.addScalar("name", StandardBasicTypes.STRING)
//.setCacheRegion("myCacheRegion")
.list();
System.out.println("list==list:"+(list==list2));
for (int i = 0; list2 != null && i < list2.size(); i++) {
Object obj = list2.get(i);
System.out.println(((String)obj));
}
//*/
tx.commit();
B) 对象缓存
Query q=session.createQuery("from Employee e");
System.out.println(q.isCacheable());
q.setCacheable(true);
List<Employee> li =q.setFirstResult(0).setMaxResults(50).list();
System.out.println(q.isCacheable());
Iterator<Employee> it=li.iterator();
while(it.hasNext())
{
Employee emp=(Employee)it.next();
System.out.println(emp);
}
//List<Employee> li2=q.list();
// Iterator<Employee> it2=li.iterator();
Query q2=session.createQuery("from Employee e ");
List<Employee> li2 =q2.setCacheable(true).setFirstResult(0).setMaxResults(50).list();
Iterator<Employee> it2=li2.iterator();
while(it2.hasNext())
{
Employee emp=(Employee)it2.next();
System.out.println(emp);
}