使用jbosscache mvcc作为hibernate的二级缓存提供者

如果使用jboss5,可以很容易的将jbosscache作为hibernate的二级缓存提供者。首先需要这样编写persistence.xml

<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/persistence"
    xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
  <persistence-unit name="tempdb" transaction-type="JTA">
    <jta-data-source>java:/DefaultDS</jta-data-source>
    <properties>
      <property name="hibernate.cache.use_second_level_cache" value="true"/>
      <property name="hibernate.cache.use_query_cache" value="true"/>
      <property name="hibernate.cache.region.factory_class" value="org.hibernate.cache.jbc2.JndiMultiplexedJBossCacheRegionFactory"/>
      <!-- region factory specific properties -->
      <property name="hibernate.cache.region.jbc2.cachefactory" value="java:CacheManager"/>
      <property name="hibernate.cache.region.jbc2.cfg.entity" value="mvcc-entity"/>
      <property name="hibernate.cache.region.jbc2.cfg.collection" value="mvcc-entity"/>
    </properties>
  </persistence-unit>
</persistence>

注意,当前的jbosscache还不支持CacheConcurrencyStrategy.NONSTRICT_READ_WRITE和CacheConcurrencyStrategy.READ_WRITE,需要将他们在代码中改为CacheConcurrencyStrategy.TRANSACTIONAL,否则hibernateentitymanager將无法启动,报如下错误

javax.persistence.PersistenceException: [PersistenceUnit: persistence] Unable to build EntityManagerFactory

...

Caused by: org.hibernate.cache.CacheException: unsupported access type [nonstrict-read-write]

当然有人会质疑为什么在带来编码限制的情况下,还引入jbosscache。理由很简单——因为它是一个分布式复制的cache,可以做到多应用服务器节点同步cache对象。当然,如果仅仅是使用单机的hibernateJPA,单节点的ehcache就够了。

相关推荐