Hibernate二级缓存的配置及实例

来源:互联网 发布:fifa聚宝盆网络繁忙 编辑:程序博客网 时间:2024/05/17 00:00

重点内容
注意:以下配置的是Hibernate 5.2.10版本
(一).二级缓存的配置步骤:

  • 1.导入ehcache的jar包
  • 2.在src目录下创建一个ehcache.xml文件,并手动配置持久化类。
  • 3.在hibernate.cfg.xml文件中开启二级缓存和设置缓存区的实现类
  • 4.使用@Cache注解声明一个类的缓存策略
  • 这里写图片描述

(二)详细步骤如下:
1.导入二级缓存所需的jar包
这里写图片描述

2.在src目录下创建一个ehcache.xml文件,并手动配置持久化类.

<diskStore path="java.io.tmpdir"/><defaultCache    maxElementsInMemory="10000"    eternal="false"    timeToIdleSeconds="120"    timeToLiveSeconds="120"    overflowToDisk="true"    /><cache name="cn.codeWang.entity.Person"    maxElementsInMemory="10000"    eternal="false"    timeToIdleSeconds="300"    timeToLiveSeconds="600"    overflowToDisk="true"    /><!-- Place configuration for your caches following -->

总结:

  1. maxElementsInMemory:设置缓存区最大存放对象的数量。
  2. eternal:设置缓存区是否永久有效。
  3. timeToIdleSeconds:设置缓存的对象多少秒没有被使用就清除。
  4. timeToLiveSeconds:设置缓存对象在过期之前可以存放多少秒。
  5. overflowToDisk:设置缓存区存放数据达到最大时,将对象存放到磁盘。

3.在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">root</property>        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>        <property name="connection.url">jdbc:mysql:///hibernate1?useUnicode=true&amp;characterEncoding=UTF-8</property>        <!-- 配置方言是非常重要!!!我这里配置的为MySQL5Dialect -->        <property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>        <!-- 配置C3P0连接池 -->        <property name="hibernate.c3p0.max_size">200</property>        <property name="hibernate.c3p0.min_size">2</property>        <property name="hibernate.c3p0.max_statements">50</property>        <property name="hibernate.c3p0.timeout"></property>        <property name="show_sql">true</property>        <property name="format_sql">true</property>        <property name="hbm2ddl.auto">update</property>         <!--开启二级缓存-->           <property name="hibernate.cache.use_second_level_cache">true</property>           <!--指定二级缓存的提供类-->           <property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property>           <!--指定二级缓存配置文件的位置-->           <property name="hibernate.cache.provider_configuration_file_resource_path">ehcache.xml</property>          <!-- 配置映射文件 -->        <mapping  class="cn.codeWang.entity.Person"/>    </session-factory></hibernate-configuration>

4.使用@Cache注解声明一个类的缓存策略

package cn.codeWang.entity;import javax.persistence.Cacheable;import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.Id;import org.hibernate.annotations.CacheConcurrencyStrategy;@Entity(name = "person")@Cacheable//选择缓存策略@org.hibernate.annotations.Cache(usage =CacheConcurrencyStrategy.READ_ONLY)public class Person {    @Id    @GeneratedValue    private int id;    private String name;    private String sex;    private String department;    public Person() {    }    public Person(String name, String sex, String department) {        super();        this.name = name;        this.sex = sex;        this.department = department;    }    public String getName() {        return name;    }    public String getSex() {        return sex;    }    public String getDepartment() {        return department;    }}

5.实例演示二级缓存的作用

package cn.codeWang.entity;import javax.persistence.Cacheable;import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.Id;import org.hibernate.annotations.CacheConcurrencyStrategy;@Entity(name = "person")@Cacheable//选择缓存策略@org.hibernate.annotations.Cache(usage =CacheConcurrencyStrategy.READ_ONLY)public class Person {    @Id    @GeneratedValue    private int id;    private String name;    private String sex;    private String department;    public Person() {    }    public Person(String name, String sex, String department) {        super();        this.name = name;        this.sex = sex;        this.department = department;    }    public String getName() {        return name;    }    public String getSex() {        return sex;    }    public String getDepartment() {        return department;    }}<ehcache>    <diskStore path="java.io.tmpdir"/>    <defaultCache        maxElementsInMemory="10000"        eternal="false"        timeToIdleSeconds="120"        timeToLiveSeconds="120"        overflowToDisk="true"        />    <!-- 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="cn.codeWang.entity.Person"        maxElementsInMemory="10000"        eternal="false"        timeToIdleSeconds="300"        timeToLiveSeconds="600"        overflowToDisk="true"        />    <!-- Place configuration for your caches following --></ehcache><?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">root</property>        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>        <property name="connection.url">jdbc:mysql:///hibernate1?useUnicode=true&amp;characterEncoding=UTF-8</property>        <!-- 配置方言是非常重要!!!我这里配置的为MySQL5Dialect -->        <property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>        <!-- 配置C3P0连接池 -->        <property name="hibernate.c3p0.max_size">200</property>        <property name="hibernate.c3p0.min_size">2</property>        <property name="hibernate.c3p0.max_statements">50</property>        <property name="hibernate.c3p0.timeout"></property>        <property name="show_sql">true</property>        <property name="format_sql">true</property>        <property name="hbm2ddl.auto">update</property>         <!--开启二级缓存-->           <property name="hibernate.cache.use_second_level_cache">true</property>           <!--指定二级缓存的提供类-->           <property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property>           <!--指定二级缓存配置文件的位置-->           <property name="hibernate.cache.provider_configuration_file_resource_path">ehcache.xml</property>          <!-- 配置映射文件 -->        <mapping  class="cn.codeWang.entity.Person"/>    </session-factory></hibernate-configuration>import java.util.Iterator;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.Transaction;import org.hibernate.boot.MetadataSources;import org.hibernate.boot.registry.StandardServiceRegistryBuilder;import org.hibernate.query.Query;import org.hibernate.service.ServiceRegistry;import org.junit.After;import org.junit.Before;import org.junit.Test;import cn.codeWang.entity.Person;public class DemoTest {    private SessionFactory sessionFactory;    private Session session;    private Transaction transaction;    @Before    public void init() {        // 创建服务注册对象        ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().configure().build();        // 创建会话工厂对象        sessionFactory = new MetadataSources(serviceRegistry).buildMetadata().buildSessionFactory();        // 会话对象        session = sessionFactory.openSession();        // 开启事物        transaction = session.beginTransaction();    }    @After    public void destory() {        // 提交事物        transaction.commit();        // 关闭会话        session.close();        // 关闭会话工厂        sessionFactory.close();    }    @Test    public void testBetching() {        Person p1 = new Person("凯耐", "男", "生产部");        Person p2 = new Person("凯丽", "女", "管理部");        Person p3 = new Person("欧陆", "男", "营销部");        session.save(p1);        session.save(p2);        session.save(p3);    }    @Test    public void testTwoCache() {        Person p = session.get(Person.class, 2);        System.out.println("姓名=" + p.getName());        p = session.get(Person.class, 2);        System.out.println("姓名=" + p.getName());    }}
1.使用同一个session对象去获得同一对象的信息    @Test    public void testTwoCache() {        Person p = session.get(Person.class, 2);        System.out.println("姓名=" + p.getName());        p = session.get(Person.class, 2);        System.out.println("姓名=" + p.getName());    }控制台输出结果:Hibernate:     select        person0_.id as id1_0_0_,        person0_.department as departme2_0_0_,        person0_.name as name3_0_0_,        person0_.sex as sex4_0_0_     from        person person0_     where        person0_.id=?姓名=凯耐姓名=凯耐2.使用不同session对象去获得同一对象的信息    @Test    public void testTwoCache() {        Person p = session.get(Person.class, 2);        System.out.println("姓名=" + p.getName());        //第二次获得session对象        session = sessionFactory.openSession();         p = session.get(Person.class, 2);        System.out.println("姓名=" + p.getName());    }控制台输出结果:Hibernate:     select        person0_.id as id1_0_0_,        person0_.department as departme2_0_0_,        person0_.name as name3_0_0_,        person0_.sex as sex4_0_0_     from        person person0_     where        person0_.id=?姓名=凯耐姓名=凯耐总结:二级缓存中的数据可适用范围是当前应用的所有回话

6.在通常情况下将具有以下特点的数据存放到二级缓存中:

  • 数据很少被修改
  • 不是很重要的数据,允许出现偶尔并发的数据
  • 不会被并发访问的数据
  • 参考数据