当谈到hibernate性能问题的时候,不可不谈的就是hibernate缓存,缓存的范围决定了缓存的生命周期以及该缓存可以被谁访问,缓存的范围可以分为3类,第一个是事物范围(即可以被当前事物所访问),第二个是进程范围(jvm级别)(可以被多个事物所访问),还有就是集群范围(缓存在集群范围内被一台或多台机器进程所共享,缓存里面的数据复制到集群环境中的每个进程节点,进程件通过通信协议来保持数据的一致性),而今天要做的笔记是关于hibernate二级缓存,即属于进程范围和集群范围,在hibernate中二级缓存范围SessionFactory级别的,hibernate本身并没有提供相应的缓存插件,而主要要来自一些缓存策略提供商(Cache Providers),像 HashTable,EHCache,OSCache,SwarmCache,JBossCache
今天主要做下hibernate的EHCache的配置及使用
1.向hibernate.cfg.xml中添加以下配置信息
如果你使用的hibernate3.2版本以下的
<property name="hibernate.cache.use_second_level_cache">true</property>
<property name="hibernate.cache.use_query_cache">true</property>
<property name="hibernate.cache.provider_class"> net.sf.ehcache.hibernate.EhCacheProvider</property>
如果你使用的是更高的版本,则配置文件应该
<property name="hibernate.cache.use_second_level_cache">true</property>
<property name="hibernate.cache.use_query_cache">true</property>
<property name="hibernate.cache.region.factory_class">net.sf.ehcache.hibernate.EhCacheRegionFactory</property>
如果在spring中则配置hibernate.properties属性为
<prop key="hibernate.cache.use_second_level_cache">true</prop>
<prop key="hibernate.cache.use_query_cache">true</prop>
<prop key="hibernate.cache.region.factory_class">net.sf.ehcache.hibernate.EhCacheRegionFactory</prop>
2.配置缓存映射(主要有xml和anotation两种方式)
映射策略主要有
(1)read-only:如果你的应用程序只需读取一个持久化类的实例,而无需对其修改, 那么就可以对其进行只读 缓
存。这是最简单,也是实用性最好的方法。甚至在集群中,它也能完美地运作。
(2)read-write 如果应用程序需要更新数据,那么使用读/写缓存 比较合适。
(3)nonstrict-read-write 如果应用程序只偶尔需要更新数据(也就是说,两个事务同时更新同一记录的情况很不常见),
也不需要十分严格的事务隔离,那么比较适合使用非严格读/写缓存策略
(还有种映射策略transactional,EHCache不支持)
在使用EHCache时,当采用xml时,你需要为实体配置相应的缓存使用策略,例如com.somecompany.someproject.domain.Country使用缓存策略
<hibernate-mapping>
<class
name="com.somecompany.someproject.domain.Country"
table="ut_Countries"
dynamic-update="false"
dynamic-insert="false"
>
...
</class>
</hibernate-mapping>
使用annotation的配置则为
@Entity
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class Country {
...
}
3.配置ehcache.xml
默认情况下ehcache.xml有个默认的缓存配置,你也可以为某个类单独配置cache,内容如下
<?xml version="1.0" encoding="UTF-8"?>
<ehcache>
<diskStore path="D:\\temp" />
<defaultCache maxElementsInMemory="10000" eternal="false"
timeToIdleSeconds="300" timeToLiveSeconds="600" overflowToDisk="true" />
<cache name="com.somecompany.someproject.domain.Country" maxEntriesLocalHeap="10000"
eternal="false" timeToIdleSeconds="300" timeToLiveSeconds="600"
overflowToDisk="true" />
</ehcache>
4.使用
如何使用,下面举个例子
public List getStreetTypes(final Country country) throws HibernateException {
final Session session = createSession();
try {
final Query query = session.createQuery(
"select st.id, st.name"
+ " from StreetType st "
+ " where st.country.id = :countryId "
+ " order by st.sortOrder desc, st.name");
query.setLong("countryId", country.getId().longValue());
query.setCacheable(true);(**这里必须指定为true,在使用Criteria也同理**)
query.setCacheRegion("query.StreetTypes");
return query.list();
} finally {
session.close();
}
}
这样二级缓存便轻松的嵌入到你的应用中去了,用log4j便可详细查看调试信息.