hibernate 缓存机制

1. 一级缓存–session
在hibernate中,oid主键标识,当在session管理权限内,当第二次在使用某个对象时会从session 缓存中获取
2. 二级缓存—sessionFactory
(1.) 内置缓存:hibernate自带的,不可卸载的,通常是在hibernate初始化阶段,hibernate会把映射元数据/预定于sql放到sessionFactory缓存中,内置缓存时只读的。

(2.)外置缓存:一个可以配置的缓存插件,可以由用户自定义配置选择缓存提供商,默认情况下sessionFactory不会启用缓存插件
外置缓存中的数据是数据库数据的复制,外置缓存的物理介质可以是内存也可以是硬盘
二级缓存提供商:
ehcache(分布式存储)
jbossCache
oscache
swamcache
3.如何配置ehcache
1.开启二级缓存

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

2.指定二级缓存提供商

<property name="hibernate.cache.region.factory_class">org.hibernate.cache.internal.EhCacheRegionFactory</property>

3.配置查询缓存

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

4.配置类级别的缓存

<class-cache usage="read-write" class="onetomany.Customer"/>
<class-cache usage="read-write" class="onetomany.Order"/>

5.外置缓存也是存在事务管理的

  1.类级别的缓存  class cache region,主要用于po对象
                             
  2.集合级别的缓存  collection cache region,用于存储集合对象
                             
  3. 查询级别缓存 query cache region,用于存储一些查询结果
                             
  4.update timestamps:更新时间戳
                             
  需要配置外置缓存的并发访问策略:
                            
  1. read-only (只读):提供了serialization数据隔离级别,对从来不修改的数据可以使用
                               
  2. read-write(读写):提供read committed 数据隔离级别,经常读但是很少被修改的数据可以使用
                               
  3. nonstrct-read-write(非严格读写):可能导致缓存中的数据和数据库中的数据不一致,提供read uncommitted级别
                         
  4. transactional (事务型):repeatable read

6.导入ehcache jar包
三个包:
ehcache-2.10.6.jar;
hibernate-ehcache-5.4.14.Final.jar;
mchange-commons-java-0.2.15.jar
ehcache.xml配置文件

<!--
  ~ Hibernate, Relational Persistence for Idiomatic Java
  ~
  ~ License: GNU Lesser General Public License (LGPL), version 2.1 or later.
  ~ See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
  -->
<ehcache>

    <!-- Sets the path to the directory where cache .data files are created.

         If the path is a Java System Property it is replaced by
         its value in the running VM.

         The following properties are translated:
         user.home - User's home directory
         user.dir - User's current working directory
         java.io.tmpdir - Default temp file path -->
    <diskStore path="java.io.tmpdir"/>


    <!--Default Cache configuration. These will applied to caches programmatically created through
        the CacheManager.

        The following attributes are required for defaultCache:

        maxInMemory       - Sets the maximum number of objects that will be created in memory
        eternal           - Sets whether elements are eternal. If eternal,  timeouts are ignored and the element
                            is never expired.
        timeToIdleSeconds - Sets the time to idle for an element before it expires. Is only used
                            if the element is not eternal. Idle time is now - last accessed time
        timeToLiveSeconds - Sets the time to live for an element before it expires. Is only used
                            if the element is not eternal. TTL is now - creation time
        overflowToDisk    - Sets whether elements can overflow to disk when the in-memory cache
                            has reached the maxInMemory limit.

        -->
    <defaultCache
        maxElementsInMemory="10000"
        eternal="false"
        timeToIdleSeconds="120"
        timeToLiveSeconds="120"
        overflowToDisk="true"
        />

    <!--Predefined caches.  Add your cache configuration settings here.
        If you do not have a configuration for your cache a WARNING will be issued when the
        CacheManager starts

        The following attributes are required for defaultCache:

        name              - Sets the name of the cache. This is used to identify the cache. It must be unique.
        maxInMemory       - Sets the maximum number of objects that will be created in memory
        eternal           - Sets whether elements are eternal. If eternal,  timeouts are ignored and the element
                            is never expired.
        timeToIdleSeconds - Sets the time to idle for an element before it expires. Is only used
                            if the element is not eternal. Idle time is now - last accessed time
        timeToLiveSeconds - Sets the time to live for an element before it expires. Is only used
                            if the element is not eternal. TTL is now - creation time
        overflowToDisk    - Sets whether elements can overflow to disk when the in-memory cache
                            has reached the maxInMemory limit.

        -->

    <!-- Sample cache named sampleCache1
        This cache contains a maximum in memory of 10000 elements, and will expire
        an element if it is idle for more than 5 minutes and lives for more than
        10 minutes.

        If there are more than 10000 elements it will overflow to the
        disk cache, which in this configuration will go to wherever java.io.tmp is
        defined on your system. On a standard Linux system this will be /tmp"
        -->
    <cache name="sampleCache1"
        maxElementsInMemory="10000"
        eternal="false"
        timeToIdleSeconds="300"
        timeToLiveSeconds="600"
        overflowToDisk="true"
        />

    <!-- Sample cache named sampleCache2
        This cache contains 1000 elements. Elements will always be held in memory.
        They are not expired. -->
    <cache name="sampleCache2"
        maxElementsInMemory="1000"
        eternal="true"
        timeToIdleSeconds="0"
        timeToLiveSeconds="0"
        overflowToDisk="false"
        /> -->

    <!-- Place configuration for your caches following -->

</ehcache>

4.代码实现

	// 演示二级缓存的
	@Test
	public void test6() {

		Session session = HibernateUtil.getSession();

		session.beginTransaction();

		Customer c1 = session.get(Customer.class, 1); // 产生sql,c1放在了一级缓存中,由于我开启了二级缓存,c1也会放在二级缓存中

		Customer c2 = session.get(Customer.class, 1);// 不产生sql,因为session没有关闭,从一级缓存中获取数据

		System.out.println(c1 == c2); // true

		session.getTransaction().commit();

		session.close(); // 一级缓存被清

		Session session1 = HibernateUtil.getSession();

		session1.beginTransaction();

		Customer c3 = session1.get(Customer.class, 1); // 不产生sql语句,从二级缓存中获取,同时c3又被纳入一级缓存中

		System.out.println(c1 == c3); // false,c3从二级缓存中获取,二级缓存中的数据是一些散装数据,它会重新new出对象

		Customer c4 = session1.get(Customer.class, 1); // 不产生sql语句,从一级缓存中获取

		System.out.println(c3 == c4); // true

		session1.getTransaction().commit();

		session1.close(); // 一级缓存被清理
	}

  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值