zoukankan      html  css  js  c++  java
  • Spring控制Hibernate的缓存机制ehcache

    首先在spring.xml中进入bean

    <prop key="hibernate.cache.use_second_level_cache">true</prop>   <!--设置缓存机制为二级缓存 -->
    <prop key="hibernate.cache.use_query_cache">true</prop>          <!--启动查询缓存 -->
    <prop key="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</prop>  <!--设置二级缓存的Provider类 -->
    <prop key="hibernate.cache.provider_configuration_file_resource_path">WEB-INF/classes/ehcache.xml</prop>   <!--设置缓存的配置文件路径 -->

    使用hibernate的缓存插件

     将ehcache.xml文件放到src下面,并配置ehcache.xml文件如下:

    <ehcache>
        <diskStore path="D:cache" />
    
        <defaultCache maxElementsInMemory="10000" eternal="false"
            timeToIdleSeconds="3600" timeToLiveSeconds="3600"
            overflowToDisk="true" diskPersistent="false"
            diskExpiryThreadIntervalSeconds="120"
            memoryStoreEvictionPolicy="LRU" />
        <cache name="net.nk.entity.DataAttr"  
            maxElementsInMemory="800" eternal="false" overflowToDisk="false"  
            timeToIdleSeconds="3600" timeToLiveSeconds="3600"   /> 
        <cache name="net.nk.entity.SmContentCategory"  
            maxElementsInMemory="800" eternal="false" overflowToDisk="false"  
            timeToIdleSeconds="3600" timeToLiveSeconds="3600"   /> 
    </ehcache>

    在hibernate的entity.hbm.xml中启动缓存机制

    <hibernate-mapping>
        <!--SM_PRODUCT表的hibernate映射描述文件 -->
        <class name="net.nk.entity.SmProduct" table="SM_PRODUCT" >
            <cache usage="read-write" region="net.nk.entity.SmProduct"/>
             <!-- ID -->
            <id name="id" type="string">
                <column name="ID" />
                <generator class="assigned" />
            </id>
            ...
      </class>
            ...
    </hibernate-mapping>    

    其中类的xml文件中的region设置要和ehcache.xml文件中的保持一致,此处是通过包名+类名的方式。

    在调用数据库数据方法时,可采取以下设置:

    protected List<POJO> getAll(Class<T> entityClass,boolean iscache) throws SSHException {
            HibernateTemplate ht = getHibernateTemplate();
            if(iscache){
                ht.setCacheQueries(true);
            }
            return ht.find("from "+entityClass.getName());//getHibernateTemplate().loadAll(entityClass);
        }

    至此,可以通过放开hibernate的show_sql来查看是否缓存机制生效了

  • 相关阅读:
    Python单元测试之unittest基础
    linux--硬链接和软链接
    12-8 istio核心功能实战-----可观察性(程访问遥测插件)
    12-7 istio核心功能实战-----可观察性(网络可视化)
    12-6 istio核心功能实战-----可观察性(分布式追踪)
    12-3 部署面向生产的istio-----核心组件
    12 ServiceMesh代表作istio-----12-1 ServiceMes、Istio架构原理
    11-7 Grafana看板和邮件报警
    11-6 监控落地
    11-4 部署前奏-Helm&Operator
  • 原文地址:https://www.cnblogs.com/hwaggLee/p/4438007.html
Copyright © 2011-2022 走看看