【hibernate二级缓存】
*二级缓存也称为进程级的缓存或SessinoFactory级的缓存,二级缓存可以被所有的session共享
*二级缓存的生命周期和SessionFactory的生命周期一致,SessionFactory可以管理缓存。
*二级缓存也是缓存实体对象的。
【二级缓存的配置和使用】
*将echcache.xml文件拷贝到src(如果使用ehcache缓存的话)
*开启二级缓存,修改hibernate.cfg.xml:
<property name="hibernate.cache.use_second_level_cache">true</property>
*指定缓存产品提供商,修改hibernate.cfg.xml文件:
<property name="hibernate.cache.provider_class">EhCacheProvider</property>
*指定使用缓存的类:
一种方式,在类的映射文件中配置:
<cache usage="read-only"/>
还有另一种方式 是在hibernate.cfg.xml中进行配置的,建议使用第二种方式:
<class-cache usage="read-only" class="myHibernate.Student"/>
注意:read-only可以避免锁的竞争问题,对于变化不太频繁的数据可以提高效率,但read-only会使数据库中的
数据在所设定的有效期内与缓存不同步,设置缓存生命周期在ehcache.xml中设置:
<defaultCache
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
overflowToDisk="true"
/>
有效时间为120s
【一级缓存session与二级缓存的交互】
设置CacheMode
* CacheMode.NORMAL :从二级缓存中读、写数据
* CacheMode.GET : 从二级缓存中读取数据,仅在数据更新时对二级缓存写数据
* CacheMode.PUT : 仅向二级缓存写数据,但不从二级缓存度数据
hinernate二级缓存的小结
最新推荐文章于 2020-03-19 16:58:39 发布