您的位置:首页 > 数据库

hibernate,hql与sql的缓存使用

2014-04-14 17:57 381 查看
getSessionFactory().evictQueries(); //清除缓存

1.在hibernate中createQuery执行hql查询的时候使用查询缓存:

getSession().createQuery(hql).setCacheable(true).setCacheRegion("user").list();

2.在hibernate中createSQLQuery执行sql时使用查询缓存:

getSession().createSQLQuery(sql).setResultTransformer(Transformers.aliasToBean(User.class)).setCacheable(true).setCacheRegion("user").list();

这样会报错,原因是That's because the aim of the second level cache is to (ultimately) cache entities that Hib knows about. I haven't
verified this but I'm not surprised that caching sql query doesn't work as those are not (directly) translated by hibernate into entities.

解决方法:

It's solutioned adding column's types to the query, using the method "addScalar()"

like this:

getSession().createSQLQuery(sql).addScalar("id", IntegerType.INSTANCE)
.addScalar("name",StringType.INSTANCE)
.addScalar("age",IntegerType.INSTANCE).setResultTransformer(Transformers.aliasToBean(User.class))
.setCacheable(true).setCacheRegion("user").list();
转自:http://www.360doc.com/content/14/0331/13/16589843_365170644.shtml

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: