hibernate4的查询缓存

在hibernate.cfg.xml加上

true //注意不是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 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 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 li =q.setFirstResult(0).setMaxResults(50).list();
System.out.println(q.isCacheable());


Iterator it=li.iterator();
while(it.hasNext())
{
Employee emp=(Employee)it.next();
System.out.println(emp);
}

//List li2=q.list();

// Iterator it2=li.iterator();
Query q2=session.createQuery("from Employee e ");
List li2 =q2.setCacheable(true).setFirstResult(0).setMaxResults(50).list();

Iterator it2=li2.iterator();
while(it2.hasNext())
{
Employee emp=(Employee)it2.next();
System.out.println(emp);
}

你可能感兴趣的:(java)