Hibernate的一二级缓存:二级缓存

本文介绍Hibernate二级缓存的配置及使用方法,包括如何在hibernate.cfg.xml中开启二级缓存,选择缓存提供者,配置EHCache的ehcache.xml文件以及在映射文件中指定缓存策略。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

SessionFactory级别的二级缓存是全局性的,应用的所有Session都共享这个二级缓存。不过二级缓存默认是关闭的,必须由程序显式开启。一旦在程序中开启了二级缓存,当Session需要抓取数据时,Session将会优先从二级缓存抓取。

Person.hbm.xml :

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC 
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
    
<hibernate-mapping package="db.domain">
    <class name="Person" table="person">
        <cache usage="read-only" region="sampleCache1"/>
        <id name="id">
            <generator class="identity"></generator>
        </id>
        <property name="name" type="string">
            <column name="name"></column>
        </property>
        <property name="age" type="integer">
            <column name="age"></column>
        </property>
    </class>
</hibernate-mapping>
hibernate.cfg.xml :

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
          "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
          "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<!-- Generated by MyEclipse Hibernate Tools.                   -->
<hibernate-configuration>

    <session-factory>
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="connection.url">jdbc:mysql://localhost:3306/test</property>
        <property name="connection.username">root</property>
        <property name="connection.password">mysqladmin</property>
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="show_sql">true</property>
        <property name="format_sql">true</property>
        <property name="hibernate.cache.use_second_level_cache">true</property>
        <property name="hibernate.cache.provider_class">
                             org.hibernate.cache.EhCacheProvider</property>
        <mapping resource="db/mapping/Person.hbm.xml"/>
    </session-factory>

</hibernate-configuration>
ehcache.xml :

<ehcache>

   
    <diskStore path="java.io.tmpdir"/>
  
    <defaultCache
        maxElementsInMemory="10000"
        eternal="false"
        timeToIdleSeconds="120"
        timeToLiveSeconds="120"
        overflowToDisk="true"
        />


    <cache name="sampleCache1"
        maxElementsInMemory="10000"
        eternal="false"
        timeToIdleSeconds="300"
        timeToLiveSeconds="600"
        overflowToDisk="true"
        />

  
    <cache name="sampleCache2"
        maxElementsInMemory="1000"
        eternal="true"
        timeToIdleSeconds="0"
        timeToLiveSeconds="0"
        overflowToDisk="false"
        />

</ehcache>

TestHibernateCache.java :

public class TestHibernateCache {

	public static void main(String[] args) {
		
		Session session=HibernateSessionFactory.getSession();
		Person person=(Person) session.get(Person.class,1);
		System.out.println(person.getId()+" "+person.getName()+" "+person.getAge());
		
		Person person2=(Person) session.get(Person.class,1);
		System.out.println(person2.getId()+" "+person2.getName()+" "+person2.getAge());
		HibernateSessionFactory.closeSession();
		
		session=HibernateSessionFactory.getSession();
		Person person3=(Person) session.get(Person.class,1);
		System.out.println(person3.getId()+" "+person3.getName()+" "+person3.getAge());
	}

}

运行TestHibernateCache.java ,控制台输出:

解释:

为了开启Hibernate的二级缓存,需要在hibernate.cfg.xml文件中设置如下属性:

<property name="hibernate.cache.use_second_level_cache">true</property>
一旦开启了二级缓存,并且设置了对某个持久化实体类启用缓存,SessionFactory就会缓存应用访问过的该实体类的每个对象,除非缓存的数据超出缓存空间。

实际应用中一般不需要开发者自己实现缓存,直接使用第三方提供的开源缓存实现即可。因此在hibernate.cfg.xml文件中设置开启缓存之后,还需要设置使用哪种二级缓存实现类:

<property name="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider
</property>
EhCacheProvider类可以在hibernate3.jar下的org.hibernate.cache包下找到。Hibernate默认使用此缓存实现。

对于EHCache缓存,它需要一个ehcache.xml配置文件,我们可以到Hibernate分发包下的etc目录下直接拷贝,稍作修改即可。对于配置文件中各属性的说明如下:

ehcache.xml中的属性说明
属性说明
maxElementsInMemory设置缓存中最多可放多少个对象
eternal设置缓存是否永久有效
timeToIdleSeconds设置缓存的对象多少秒没有被使用就会清理掉
timeToLiveSeconds设置缓存的对象在过期之前可以缓存多少秒
overflowToDisk设置当内存中缓存的记录达到maxElementsInMemory时是否被持久化到硬盘中,保存路径由<diskStore.../>元素指定。
最后在Xxx.hbm.xml.文件中的<class.../>元素、或<set.../>、<list.../>等集合元素内使用<cache.../>元素指定缓存策略。

<cache.../>元素的usage属性值read-only:如果应用程序只需要读取持久化实体的对象,无须对其进行修改,那么就可以对其设置“只读”缓存策略。这是最简单也最实用的缓存策略。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值