您的位置:首页 > 其它

Hibernate中的缓存机制

2017-09-24 10:34 281 查看
表现层:struts2

业务逻辑层:

持久层:Hibernate

Hibernate中的缓存机制

一:一级缓存:默认是开启的,不需要做任何的配置

session.evict(news); 清除单个缓存

session.clear(); 清除所有缓存

二:二级缓存:默认是没有开启的,需要手工配置
1. 需要在Hibernate.cfg.xml中进行配置


true

2. 根据需要配置二级缓存的提供商 常用ehcache oscache

需要引入ehcache依赖的jar包

在Hibernate.cfg.xml中进行配置 指定二级缓存的提供商

org.hibernate.cache.internal.EhCacheRegionFactory

3. 引入ehcache.xml文件

4.在需要放入二级缓存的类的映射文件中加上

三:查询缓存:
1.在hibernate.cfg.xml配置文件中配置以下代码


true

2. 在查询方法中Query语句执行,返回值前调用.setCacheable(true)

eg:通过id查询

public News getNewsByIdQuery(long newsId){

News n=null;

Session session=null;

try{

session=SessionFactoryUtils.openSession();

String hql=”from News where id=”+newsId;

n=(News)session.createQuery(hql)

.setCacheable(true) //返回值前调用.setCacheable(true)

.uniqueResult();

}catch(Exception e){

e.printStackTrace();

}finally{

if(session!=null){

session.close();

}

}

return n;

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