最近项目中需要处理hibernate缓存:
网络上看了些文章 总结下:
大道理,原理就不说了,写点直接用的。
第一种方法:
Spring 中配置
<property name="hibernateProperties"> <props> <prop key="hibernate.dialect"> org.hibernate.dialect.MySQLDialect </prop> <prop key="hibernate.show_sql">true</prop> <prop key="hibernate.max_fetch_depth">0</prop> <prop key="hibernate.generate_statistics">true</prop> <prop key="hibernate.cache.use_query_cache">true</prop> <prop key="hibernate.cache.use_second_level_cache">true</prop> <prop key="cglib.use_reflection_optimizer">false</prop> <prop key="hibernate.cache.provider_class">org.hibernate.cache.HashtableCacheProvider</prop> <prop key="hibernate.query.factory_class">org.hibernate.hql.ast.ASTQueryTranslatorFactory</prop> </props> </property>
<!-- 配置hibernate 模板代码 --> <bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate"> <property name="sessionFactory" ref="sessionFactory"></property> <property name="cacheQueries" value="true"></property> </bean>
Src 下 ehcache.xml
<?xml version="1.0" encoding="UTF-8"?> <ehcache> <diskStore path="java.io.tmpdir" /> <defaultCache maxElementsInMemory="10000" eternal="false" overflowToDisk="true" timeToIdleSeconds="300" timeToLiveSeconds="180" diskPersistent="false" diskExpiryThreadIntervalSeconds="120" /> </ehcache>
实体配置:
@Entity
@Cache(usage=CacheConcurrencyStrategy.READ_WRITE)
(1) usage: 提供缓存对象的事务隔离机制,可选值有以下几种
(NONE, READ_ONLY, NONSTRICT_READ_WRITE, READ_WRITE, TRANSACTIONAL)
(2) region (optional): 指定缓存的区域,默认是类的全限定名。利用缓存区域,可以更精确的指定每个区域的缓存超前策略。如果指定了缓存区域前缀(在 hibernate.cfg.xml中设置cache.region_prefix属性为一个字符串),则所有的缓存区域名前将加上这个前缀。
(3) include (optional): all to include all properties, non-lazy to only include non lazy properties (default all).
如果不是使用annotation的话,则是在Hbm文件中添加cache usage="read-only"
此种方法制定类(对象)的缓存
第二种方法:
Spring 配置文件一样:
添加java方法:
public List findByHqlForCache(String queryString){
Session session = this.getSession();
Query query = session.createQuery(queryString);
query.setCacheable(true);
List list = query.list();
session.flush();
return list;
}
在使用的时候引用上面的方法,此种方式制定那条HQL 的缓存