spring+hibernate 二级缓存 配置+java使用实例

来源:互联网 发布:淘宝衣服商标被撕掉 编辑:程序博客网 时间:2024/04/30 01:14

网上有很多关于spring+hibernate 二级缓存的配置文章,但是java使用实例不是很多,所以我把这两个加在一起来写一个文章,一个方便自己查阅,一方面希望能够给查资料的人们提供些许方便。

这里使用的环境:spring3.0+hibernate3.2+ehcache。相关环境配置和jar包引入略。

配置:

1、hibernate-mapping.xml配置文件中添加:

[html] view plaincopy在CODE上查看代码片派生到我的代码片
  1. <property name="hibernate.cache.use_second_level_cache">true</property>  
  2. <property name="hibernate.cache.use_query_cache">true</property>  
  3.     <property name="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</property>  
  4.       

2、Hibernate允许在类和集合的粒度上设置第二级缓存。在映射文件中,<class>和<set>元素都有一个<cache>子元素,这个子元素用来配置二级缓存。
示例:以category(产品类别)和product(产品)的映射为例:

 修改要配置缓存的那个持久化类的对象关系映射文件:

Category.hbm.xml 

[html] view plaincopy在CODE上查看代码片派生到我的代码片
  1. <?xml version="1.0" encoding="utf-8"?>     
  2.   
  3. <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"     
  4. "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">     
  5. <hibernate-mapping>     
  6.     <class name="org.qiujy.domain.cachedemo.Category" table="categories">     
  7.        <!—     
  8.              配置缓存,必须紧跟在class元素后面     
  9.             对缓存中的Category对象采用读写型的并发访问策略     
  10.         -->     
  11.        <cache usage="read-write"/>     
  12.            
  13.        <id name="id" type="java.lang.Long">     
  14.            <column name="id" />     
  15.            <generator class="native" />     
  16.        </id>     
  17.        <!-- 配置版本号,必须紧跟在id元素后面 -->     
  18.        <version name="version" column="version" type="java.lang.Long" />     
  19.            
  20.        <property name="name" type="java.lang.String">     
  21.            <column name="name" length="32" not-null="true"/>     
  22.        </property>     
  23.            
  24.        <property name="description" type="java.lang.String">     
  25.            <column name="description" length="255"/>     
  26.        </property>     
  27.            
  28.        <set name="products" table="products" cascade="all" inverse="true">     
  29.            <!-- Hibernate只会缓存对象的简单属性的值,     
  30.        要缓存集合属性,必须在集合元素中也加入<cache>子元素     
  31.        而Hibernate仅仅是把与当前持久对象关联的对象的OID存放到缓存中。     
  32. 如果希望把整个关联的对象的所有数据都存入缓存,     
  33. 则要在相应关联的对象的映射文件中配置<cache>元素     
  34.            -->     
  35.            <cache usage="read-write"/>     
  36.                
  37.            <key column="categoryId" not-null="true"/>     
  38.            <one-to-many class="org.qiujy.domain.cachedemo.Product"/>     
  39.        </set>     
  40.            
  41.     </class>     
  42. </hibernate-mapping>  
Product.hbm.xml
[html] view plaincopy在CODE上查看代码片派生到我的代码片
  1. <?xml version="1.0" encoding="utf-8"?>     
  2. <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"     
  3. "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">     
  4. <hibernate-mapping>     
  5.     <class name="org.qiujy.domain.cachedemo.Product" table="products">     
  6.            
  7.        <cache usage="read-write"/>     
  8.            
  9.        <id name="id" type="java.lang.Long">     
  10.            <column name="id" />     
  11.            <generator class="native" />     
  12.        </id>     
  13.        <!-- 配置版本号,必须紧跟在id元素后面 -->     
  14.        <version name="version" column="version" type="java.lang.Long" />     
  15.            
  16.        <property name="name" type="java.lang.String">     
  17.            <column name="name" length="32" not-null="true"/>     
  18.        </property>     
  19.            
  20.        <property name="description" type="java.lang.String">     
  21.            <column name="description" length="255"/>     
  22.        </property>     
  23.            
  24.        <property name="unitCost" type="java.lang.Double">     
  25.            <column name="unitCost" />     
  26.        </property>     
  27.            
  28.        <property name="pubTime" type="java.util.Date">     
  29.            <column name="pubTime" not-null="true" />     
  30.        </property>     
  31.            
  32.        <many-to-one name="category"     
  33.                 column="categoryId"     
  34.                class="org.qiujy.domain.cachedemo.Category"     
  35.                cascade="save-update"     
  36.                 not-null="true">     
  37.         </many-to-one>     
  38.            
  39.     </class>     
  40. </hibernate-mapping>  
3、编辑ehcache.xml文件:
[html] view plaincopy在CODE上查看代码片派生到我的代码片
  1. <ehcache>     
  2.     <diskStore path="c:\\ehcache\"/>     
  3.     <defaultCache     
  4.         maxElementsInMemory="10000"     
  5.         eternal="false"     
  6.         timeToIdleSeconds="120"     
  7.         timeToLiveSeconds="120"     
  8.         overflowToDisk="true"       
  9.         />     
  10.             
  11.     <!-- 设置Category类的缓存的数据过期策略 -->     
  12.     <cache name="org.qiujy.domain.cachedemo.Category"     
  13.         maxElementsInMemory="100"     
  14.         eternal="true"     
  15.         timeToIdleSeconds="0"     
  16.         timeToLiveSeconds="0"     
  17.         overflowToDisk="false"     
  18.         />     
  19.             
  20.      <!-- 设置Category类的products集合的缓存的数据过期策略 -->     
  21.      <cache name="org.qiujy.domain.cachedemo.Category.products"     
  22.         maxElementsInMemory="500"     
  23.         eternal="false"     
  24.         timeToIdleSeconds="300"     
  25.         timeToLiveSeconds="600"     
  26.         overflowToDisk="true"     
  27.         />     
  28.             
  29.     <cache name="org.qiujy.domain.cachedemo.Product"     
  30.         maxElementsInMemory="500"     
  31.         eternal="false"     
  32.         timeToIdleSeconds="300"     
  33.         timeToLiveSeconds="600"     
  34.         overflowToDisk="true"     
  35.         />    
[html] view plaincopy在CODE上查看代码片派生到我的代码片
  1. <cache name="workUnitHisCache"  
  2.            maxElementsInMemory="10000"  
  3.            eternal="false"  
  4.            timeToIdleSeconds="2400"  
  5.            timeToLiveSeconds="2400"  
  6.            overflowToDisk="false"/>  
  7.         
  8. </ehcache>  

到此基本配置文件完成了。

使用:(以workUnitHisCache为例,上面两个是为了说明多对一关系的配置,最后一个的hbm.xml文件没有贴出来,知道怎么配置就可以了)

代码:

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. @Service  
  2. public class WorkUnitHisServiceImpl {  
  3.       
  4.     private static final Logger log = LoggerFactory.getLogger(WorkUnitHisServiceImpl.class);  
  5.     @Autowired  
  6.     private ITestdao testdao;   
  7.       
  8.     @Autowired //spring注解方式注入cache  
  9.     private Cache workUnitHisCache;  
  10.       
  11.     private Boolean useCache = true;  
  12.       
  13.     @SuppressWarnings("unchecked")  
  14.     @Override  
  15.     public PageResult<Test> test(  
  16.             String condition) {  
  17.   
  18.         //在缓存中取值(如果缓存中没有值,则从数据库中取值)  
  19.         PageResultVO<WorkUnitHisCount> pageCache = null;  
  20.         if (this.useCache) { //是否使用cache  
  21.             if (log.isDebugEnabled()) {  
  22.                 log.debug("WorkUnitHisCount缓存开启,从缓存中获取WorkUnitHisCount,typeCode:" + "");  
  23.             }  
  24.             //在缓存中取值,get()参数为放入缓存中的key  
  25.             Element element = this.workUnitHisCache.get(condition);  
  26.             if (element != null && element.getObjectValue() != null) {  
  27.                 //缓存中放入什么,则此处可以取出什么  
  28.                 pageCache = (PageResultVO<WorkUnitHisCount>)element.getObjectValue();  
  29.             }  
  30.         }  
  31.         if (pageCache == null) { //如果该对象为null,则缓存中没有对象,需要从数据库中取数据并放入到缓存中  
  32.             if (log.isDebugEnabled()) {  
  33.                 log.debug("从数据库中获取WorkUnitHisCount,typeCode:" + "" );  
  34.             }  
  35.             //在数据库中取值  
  36.             pageCache = testdao.testget(condition);  
  37.             //将结果放入到缓存中  
  38.             if (this.useCache) {  
  39.                 Element element = new Element(condition, pageCache);  
  40.                 this.workUnitHisCache.put(element);  
  41.             }  
  42.         }  
  43.         return pageCache;  
  44.     }  
  45. }  

其中:

@Autowired
private Cache workUnitHisCache;

如果不采用注解的方式,java类中增加get、set方法,spring配置文件中如下配置:

[html] view plaincopy在CODE上查看代码片派生到我的代码片
  1. <?xml version="1.0" encoding="UTF-8" standalone="no"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.     xmlns:p="http://www.springframework.org/schema/p" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  4.     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">  
  5.   
  6.     <!-- ================================================ -->  
  7.     <!--       echcache extention config                  -->  
  8.     <!-- ================================================ -->  
  9.     <bean  id="cacheManager"  class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">   
  10.           <property  name="configLocation" value="classpath:ehcache.xml"/>     
  11.      </bean >   
  12.        
  13.     <bean  id ="workUnitHisCache"  class ="org.springframework.cache.ehcache.EhCacheFactoryBean">   
  14.          <property name="cacheManager" ref="cacheManager" />  
  15.          <property name="cacheName" value="workUnitHisCache" />  
  16.     </bean>   
  17.       
  18. </beans>  
到此结束了。欢迎高手指点,有问题者及时提问。
0 1