首页 > 代码库 > 配置Hibernate二级缓存

配置Hibernate二级缓存

 

首先找到配置EHCahe二级缓存需要添加的jar

hibernate-release-4.1.9.Final→liboptional→ehcache→下的ehcache-core-2.4.3.jar和hibernate-ehcache-4.1.9.Final.jar还有slf4j-api-1.6.1.jar!

然后再从hibernate-release-4.1.9.Final→project→etc→把ehcache.xml复制到src目录下.把缓存.xml没用的都删了,留下最终:

<ehcache>

     <!-- 缓存路径 -->

    <diskStore path="E:\SecondCache"/>      //自己配置

    <defaultCache

        maxElementsInMemory="10000"

        eternal="false"

        timeToIdleSeconds="120"

        timeToLiveSeconds="120"

        overflowToDisk="true"

        />

</ehcache>

 

再在hibernate.cfg.xml里开启和配置缓存:

<!-- 开启二级缓存 -->

<property name="hibernate.cache.use_second_level_cache">true</property>

<!-- 高速缓存提供程序 -->

<property name="hibernate.cache.region.factory_class">

org.hibernate.cache.ehcache.EhCacheRegionFactory

</property>

最后在实体类的xml文件里设置缓存: <cache usage="read-write"/>

:

  <hibernate-mapping>

       <class name="cn.jnit.bean.User" table="T_user">

       <cache usage="read-write"/>

         <id name="id">

           <generator class="sequence">

           </generator>

         </id>

         <property name="pwd"></property>

         <property name="name"></property>

         <one-to-one name="ud" class="cn.jnit.bean.UserDetail" cascade="all" ></one-to-one>

       </class>

</hibernate-mapping>

如果查询的是集合的话:也需要在<SET>里设置:

<hibernate-mapping>

<class name="cn.jbit.bean.Dept" table="DEPT">

<cache usage="read-write" />

<id name="deptno">

<generator class="sequence"></generator>

</id>

<property name="dname"></property>

<property name="loc"></property>

<set name="emps" cascade="save-update" inverse="true" order-by="empno desc"

lazy="false">

<cache usage="read-only" />

<key column="deptno"></key>

<one-to-many class="cn.jbit.bean.Emp" />

</set>

</class>

</hibernate-mapping>.

++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

如果配置文件里没有<SET>,不必设置,QUERY的查询语句优化的话,需要开启查询缓存→<!-- 开启查询缓存 -->

<property name="hibernate.cache.query_cache_factory">true</property>

下面是我一对一关系里测试的数据,切记:

不 是 Iterator<User> iterator=ses.createQuery(hql).setCacheable(true). list().iterator();

 

Iterator<User> iterator=ses.createQuery(hql).setCacheable(true).iterate();

 

Session ses=HibernateSessionFactory.getSession();

String hql="from User";

List<User> list = ses.createQuery(hql).setCacheable(true).list();

System.out.println(list.size());

HibernateSessionFactory.closeSession();

ses=HibernateSessionFactory.getSession();

Iterator<User> iterator = ses.createQuery(hql).setCacheable(true).iterate();

while (iterator.hasNext()) {

User user = (User) iterator.next();

System.out.println(user.getId());

}

ses.close();

配置Hibernate二级缓存