Hibernate学习笔记----二级缓存

来源:互联网 发布:淘宝卖家支付宝在哪里 编辑:程序博客网 时间:2024/04/30 05:59

使用二级缓存的步骤:

1.加入二级缓存所需要的jar包和配置文件

1).加入hibernate-release-4.3.11.Final/lib/optional/ehcache下的jar包

2).加入hibernate-release-4.3.11.Final/project/etc/ehcache.xml到类目录下

2.配置hibernate.cfg.xml

1).配置启用二级缓存

<propertyname="cache.use_second_level_cache">true</property>

2).配置使用二级缓存的产品

<propertyname="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property>

(注意:如果在hibernate.properties里面直接拷这个路径是有问题的,建议在引用包里面直接找)

3).配置哪些类使用了二级缓存

<class-cache usage="read-write" class="cn.limbo.hibernate.entities.Employee"/>

实际上也可以在hbm.xml文件中配置对哪些类使用二级缓存,以及二级缓存的策略是什么。

例子:

hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE hibernate-configuration PUBLIC"-//Hibernate/Hibernate Configuration DTD 3.0//EN""http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"><hibernate-configuration>    <session-factory>    <!--数据库信息-->          <property name="connection.username">root</property>          <property name="connection.password">123456</property>          <property name="connection.driver_class">com.mysql.jdbc.Driver</property>          <property name="connection.url">jdbc:mysql:///hibernate</property>            <!--hibernate基本信息-->          <!--hibernate使用的数据库方言-->          <property name="hiberate.dialect">org.hibernate.dialect.MySQLInnoDBDialect</property>          <!--执行操作时,是否在控制台打印SQL-->          <property name="hibernate.show_sql">true</property>          <!--是否对SQL格式化-->          <property name="hibernate.format_sql">true</property>          <!--指定声称数据库表的策略-->          <property name="hibernate.hbm2ddl.auto">update</property>                  <!--配置c3p0数据源-->         <!--数据库连接池最大连接数-->         <property name="hibernate.c3p0.max_size">10</property>         <!--数据库连接池最小连接数-->         <property name="hibernate.c3p0.min_size">5</property>         <!--当数据库连接池中连接耗尽时,同一时刻获取多少个数据库连接-->         <property name="c3p0.acquire_increment">2</property>           <!--数据库连接池中连接对象在多长时间没有使用过后,就应该被销毁-->         <property name="c3p0.idle_test_period">2000</property>         <!--表示连接池检测线程多长时间检测一次池内的所有对象是否超时,         连接池本身不会把自己从连接池中中移除,而是专门又一个线程按照一定的时间间隔来做这件事,         这个线程通过比较连接对象最后一次被使用时间和当前时间的时间差和timeout做比较,进而决定是否销毁这个连接对象-->         <property name="c3p0.timeout">2000</property>           <!--缓存Statement对象的数量-->         <property name="c3p0.max_statements">10</property>             <!--以下两个配置项对mysql无效,对oracle有效,有显著的性能提升-->         <!--设定JDBC的statement读取数据的时候的每次从数据库中取出的记录条数,100 是最合适的 -->         <property name="hibernate.jdbc.fetch_size">100</property>           <!--设定数据库进行批量删除,批量更新和批量插入的时候的批次大小-->         <property name="hibernate.jdbc.batch_size">30</property>         <!-- 启用二级缓存 -->        <property name="cache.use_second_level_cache">true</property>        <!-- 配置使用二级缓存的产品 -->        <property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property>        <!--指定关联的.hbm.xml文件-->        <mapping resource="cn/limbo/hibernate/entities/Department.hbm.xml"/>        <mapping resource="cn/limbo/hibernate/entities/Employee.hbm.xml"/>                <!--对那个类启用二级缓存-->        <!-- <class-cache usage="read-write" class="cn.limbo.hibernate.entities.Employee"/> -->    </session-factory></hibernate-configuration>
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"><!-- Generated 2016-7-24 23:26:24 by Hibernate Tools 3.5.0.Final --><hibernate-mapping>    <class name="cn.limbo.hibernate.entities.Employee" table="EMPLOYEES">    <cache usage="read-write"/>        <id name="id" type="java.lang.Integer">            <column name="ID" />            <generator class="native" />        </id>        <property name="name" type="java.lang.String">            <column name="NAME" />        </property>        <property name="email" type="java.lang.String">            <column name="EMAIL" />        </property>        <property name="salary" type="double">            <column name="SALARY" />        </property>        <many-to-one name="department" class="cn.limbo.hibernate.entities.Department" column="DEPARTMENT_ID">        </many-to-one>    </class>    <query name="salaryEmps"><![CDATA[From Employee e WHERE e.salary > :minSal AND e.salary < :maxSal]]></query></hibernate-mapping>

2.对集合使用二级缓存

1.在cfg.xml中配置

<class-cache usage="read-write" class="cn.limbo.hibernate.entities.Employee"/><class-cache usage="read-write" class="cn.limbo.hibernate.entities.Department"/><!--指定集合元素使用二级缓存--><collection-cache usage="read-write" collection="cn.limbo.hibernate.entities.Department.employees"/> 

2.在hbm.xml

<set name="employees" table="EMPLOYEES" inverse="true" lazy="true">        <cache usage="read-write"/>            <key>                <column name="DEPARTMENT_ID" />            </key>            <one-to-many class="cn.limbo.hibernate.entities.Employee" />        </set>
注意:还需要配置集合中的元素对应的持久化类也使用二级缓存

3.ehcache.xml配置详解

<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 -->         <!-- 指定一个目录,当EHCache把数据写到硬盘上的时候,把数据写到这个目录下  -->    <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.        -->        <!-- 设置缓存的默认数据过期策略 -->        <!--         name:缓存名称。对于类而言,名称就是类名,如:cn.limbo.hibernate.entities.Department                      对于集合而言,名称是类名加属性名,如:cn.limbo.hibernate.entities.Department.employees       maxElementsInMemory:可存放的对象最大的数目。         eternal:对象是否永久有效,true表示永不过期,此时忽略 timeToIdleSeconds, timeToLiveSeconds失效。默认为false;       timeToIdleSeconds:设置对象在失效前的允许闲置时间(单位:秒)。仅当eternal=false对象不是永久有效时使用,可选属性,默认值是0,也就是可闲置时间无穷大。         timeToLiveSeconds:设置对象在失效前允许存活时间(单位:秒)。最大时间介于创建时间和失效时间之间。仅当eternal=false对象不是永久有效时使用,默认是0.,也就是对象存活时间无穷大。         overflowToDisk:当内存中对象数量达到maxElementsInMemory时,Ehcache将会对象写到磁盘中。         diskSpoolBufferSizeMB:这个参数设置DiskStore(磁盘缓存)的缓存区大小。默认是30MB。每个Cache都应该有自己的一个缓冲区。         maxElementsOnDisk:硬盘最大缓存个数。         diskPersistent:是否缓存虚拟机重启期数据 Whether the disk store persists between restarts of the Virtual Machine. The default value is false.         diskExpiryThreadIntervalSeconds:磁盘失效线程运行时间间隔,默认是120秒。         memoryStoreEvictionPolicy:当达到maxElementsInMemory限制时,Ehcache将会根据指定的策略去清理内存。默认策略是LRU(最近最少使用)。你可以设置为FIFO(先进先出)或是LFU(较少使用)。         clearOnFlush:内存数量最大时是否清除。      -->      <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.查询缓存

默认情况下,设置的缓存对HQL及QBC查询时无效,但是可以通过以下方式时期有效
1).在hibernate配置文件中声明开启查询缓存

<propertyname="cache.use_query_cache">true</property>


2).再调用Query或者Criteria中的setCacheable(true)

@Testpublic void testQuerySecondLevelCache(){Query query = session.createQuery("FROM Employee");query.setCacheable(true);List<Employee> employees = query.list();System.out.println(employees.size());employees = query.list();System.out.println(employees.size());}


3).查询缓存依赖于二级缓存



0 0
原创粉丝点击