hibernate之2----hibernate缓存

来源:互联网 发布:level2免费版软件 编辑:程序博客网 时间:2024/05/29 08:56

      hibernate缓存,包括一级缓存、二级缓存和查询缓存。

     其中,一级缓存的生命周期随着session的生命周期。在session 接口实现类org.hibernate.internal.SessionImpl中,persistenceContext 属性中保存着一级缓存;

   private transient StatefulPersistenceContext persistenceContext //属性保存着一级缓存对象

     org.hibernate.engine.internal.StatefulPersistenceContext类中,一级缓存指的就是entitiesByKey属性;如下图:

public class StatefulPersistenceContext implements PersistenceContext {private static final CoreMessageLogger LOG = Logger.getMessageLogger(CoreMessageLogger.class,StatefulPersistenceContext.class.getName());private static final boolean TRACE_ENABLED = LOG.isTraceEnabled();private static final int INIT_COLL_SIZE = 8;private SessionImplementor session;// Loaded entity instances, by EntityKey       private Map<EntityKey, Object> entitiesByKey;  //一级缓存


    而一级缓存的主要作用在于:对持久化对象的多次操作都保存在一级缓存中,当执行session.flush时,才更新到数据库中。

    二级缓存,生命周期与sessionFactory保持一致,用于保存一些全局的数据,不会轻易更改的数据,例如菜单,权限等信息。

    SessionFactoryImpl类中,用于二级缓存的属性如下:

 

   private final transient Map<String,EntityPersister> entityPersisters; //对象缓存
   private final transient Map<String,CollectionPersister> collectionPersisters;//集合缓存

   插入数据到二级缓存的常用方法有load/get,Query对象的list方法等;取出的方法有load/get,Query对象的iterate方法。

   二级缓存的配置有:hibernate.cfg.xml中加入:

<!-- 二级缓存 sessionFactory级别 -->       <property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property>         <property name="hibernate.cache.use_second_level_cach">true</property>
<!-- 配置二级缓存策略和相应的类 -->        <class-cache usage="read-only" class="pojo.User"/>

  ehcache的配置文件ehcache.xml如下:

 

<?xml version="1.0" encoding="UTF-8"?><ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    xsi:noNamespaceSchemaLocation="ehcache.xsd" updateCheck="true"    monitoring="autodetect" dynamicConfig="true">    <!-- 指定持久化数据时的磁盘目录 -->    <diskStore path="e:\\TEMP1"/>    <!--设置默认的 缓存过期策略 -->    <defaultCache            maxElementsInMemory="12"            eternal="false"            timeToIdleSeconds="1200"            timeToLiveSeconds="1200"            overflowToDisk="false"            maxElementsOnDisk="10000000"            diskPersistent="false"            diskExpiryThreadIntervalSeconds="120"            memoryStoreEvictionPolicy="LRU"            />     <!--设置指定类的缓存过期策略 -->   <Cache            name="pojo.User"            maxElementsInMemory="3"             eternal="false"            timeToIdleSeconds="120"            timeToLiveSeconds="120"            overflowToDisk="true"            maxElementsOnDisk="10000000"            diskPersistent="false"            diskExpiryThreadIntervalSeconds="120"            memoryStoreEvictionPolicy="LRU"            /></ehcache>

    针对一二级缓存中只能保存对象信息,hibernate查询缓存则中可以保存对象中部分属性的信息,如:只保存用户姓名等。其中,需要在核心配置文件中加下如下一句话:

  

 <!-- 开启查询缓存 -->        <property name="cache.use_query_cache">true</property>
  以及在程序中设置query.setCacheable(true);

 下面是使用查询缓存的demo代码,查询用户表中的用户名字:

 

        @Testpublic void useQueryCache(){Transaction transaction = session.beginTransaction();Query query=session.createQuery("select username from User");query.setCacheable(true);System.out.println(query.list());query=session.createQuery("select username from User");query.setCacheable(true);System.out.println(query.list());transaction.commit();}
   结果:

Hibernate: select user0_.username as col_0_0_ from user user0_[admin][admin]




   

 
原创粉丝点击