zoukankan      html  css  js  c++  java
  • hibernate 二级缓存

    版权声明:本文为博主原创文章,未经博主同意不得转载。

    https://blog.csdn.net/qilixiang012/article/details/28017885

    Hibernate 缓存

    • 缓存(Cache): 计算机领域非常通用的概念。它介于应用程序和永久性数据存储源(如硬盘上的文件或者数据库)之间。其作用是减少应用程序直接读写永久性数据存储源的频率,从而提高应用的运行性能。缓存中的数据是数据存储源中数据的拷贝。

      缓存的物理介质一般是内存

    • Hibernate中提供了两个级别的缓存
      • 第一级别的缓存是 Session 级别的缓存。它是属于事务范围的缓存。这一级别的缓存由 hibernate 管理的
      • 第二级别的缓存是 SessionFactory 级别的缓存,它是属于进程范围的缓存

    SessionFactory 级别的缓存

    • SessionFactory 的缓存能够分为两类:
      • 内置缓存: Hibernate 自带的, 不可卸载. 通常在 Hibernate 的初始化阶段, Hibernate 会把映射元数据和提前定义的 SQL 语句放到 SessionFactory 的缓存中, 映射元数据是映射文件里数据(.hbm.xml 文件里的数据)的复制. 该内置缓存是仅仅读的.
      • 外置缓存(二级缓存): 一个可配置的缓存插件.在默认情况下, SessionFactory 不会启用这个缓存插件. 外置缓存中的数据是数据库数据的复制, 外置缓存的物理介质能够是内存或硬盘

    使用 Hibernate 的二级缓存

    • 适合放入二级缓存中的数据:
      • 非常少被改动
      • 不是非常重要的数据, 同意出现偶尔的并发问题
    • 不适合放入二级缓存中的数据:
      • 常常被改动
      • 財务数据, 绝对不同意出现并发问题
      • 与其它应用程序共享的数据

    Hibernate 二级缓存的架构


    二级缓存的并发訪问策略
    • 两个并发的事务同一时候訪问持久层的缓存的同样数据时, 也有可能出现各类并发问题.
    • 二级缓存能够设定下面 4 种类型的并发訪问策略, 每一种訪问策略相应一种事务隔离级别
      • 非严格读写(Nonstrict-read-write): 不保证缓存与数据库中数据的一致性. 提供 Read Uncommited 事务隔离级别, 对于极少被改动, 并且同意脏读的数据, 能够採用这样的策略
      • 读写型(Read-write):提供 Read Commited 数据隔离级别.对于常常读可是非常少被改动的数据, 能够採用这样的隔离类型, 由于它能够防止脏读
      • 事务型(Transactional): 仅在受管理环境下适用. 它提供了 Repeatable Read 事务隔离级别. 对于常常读可是非常少被改动的数据, 能够採用这样的隔离类型, 由于它能够防止脏读和不可反复读
      • 仅仅读型(Read-Only):提供 Serializable 数据隔离级别, 对于从来不会被改动的数据, 能够採用这样的訪问策略


    管理 Hibernate 的二级缓存
    • Hibernate 的二级缓存是进程或集群范围内的缓存
    • 二级缓存是可配置的的插件, Hibernate 同意选用下面类型的缓存插件:
      • EHCache: 可作为进程范围内的缓存, 存放数据的物理介质能够使内存或硬盘, 对 Hibernate 的查询缓存提供了支持
      • OpenSymphony OSCache:可作为进程范围内的缓存, 存放数据的物理介质能够使内存或硬盘, 提供了丰富的缓存数据过期策略, 对 Hibernate 的查询缓存提供了支持
      • SwarmCache: 可作为集群范围内的缓存, 但不支持 Hibernate 的查询缓存
      • JBossCache:可作为集群范围内的缓存, 支持 Hibernate 的查询缓存
    • 4 种缓存插件支持的并发訪问策略(x 代表支持, 空白代表不支持)



    配置进程范围内的二级缓存
    • 配置进程范围内的二级缓存的步骤:
      • 选择合适的缓存插件: EHCache(jar 包和 配置文件), 并编译器配置文件
      • 在 Hibernate 的配置文件里启用二级缓存并指定和 EHCache 相应的缓存适配器
      • 选择须要使用二级缓存的持久化类, 设置它的二级缓存的并发訪问策略
        • <class> 元素的 cache 子元素表明 Hibernate 会缓存对象的简单属性, 但不会缓存集合属性, 若希望缓存集合属性中的元素, 必须在 <set> 元素中增加 <cache> 子元素
        • 在 hibernate 配置文件里通过 <class-cache/> 节点配置使用缓存


    1. 使用 Hibernate 二级缓存的步骤:
    1). 增加二级缓存插件的 jar 包及配置文件:

    I. 复制 hibernate-release-4.2.4.Finalliboptionalehcache*.jar 到当前 Hibrenate 应用的类路径下.

    II. 复制 hibernate-release-4.2.4.Finalprojectetcehcachexml 到当前 WEB 应用的类路径下

    2). 配置 hibernate.cfg.xml

    I. 配置启用 hibernate 的二级缓存
    <property name="cache.use_second_level_cache">true</property>
    II 配置hibernate二级缓存使用的产品
    <property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property>
    III. 配置对哪些类使用 hibernate 的二级缓存
    <class-cache usage="read-write" class="com.atguigu.hibernate.entities.Employee"/>
    实际上也能够在 .hbm.xml 文件里配置对哪些类使用二级缓存, 及二级缓存的策略是什么.

    2). 集合级别的二级缓存的配置

    I. 配置对集合使用二级缓存

    <collection-cache usage="read-write" collection="com.atguigu.hibernate.entities.Department.emps"/>

    也能够在 .hbm.xml 文件里进行配置

    <set name="emps" table="GG_EMPLOYEE" inverse="true" lazy="true">
    	<cache usage="read-write"/>
        <key>
            <column name="DEPT_ID" />
        </key>
        <one-to-many class="com.atguigu.hibernate.entities.Employee" />
    </set>
    II. 注意: 还须要配置集合中的元素相应的持久化类也使用二级缓存! 否则将会多出 n 条 SQL 语句.

    3). ehcache 的 配置文件: ehcache.xml


    4). 查询缓存: 默认情况下, 设置的缓存对 HQL 及 QBC 查询时无效的, 但能够通过下面方式使其是有效的

    I. 在 hibernate 配置文件里声明开启查询缓存

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

    II. 调用 Query 或 Criteria 的 setCacheable(true) 方法
    III. 查询缓存依赖于二级缓存

    ehcache.xml

    <diskStore>: 指定一个文件夹:当 EHCache 把数据写到硬盘上时, 将把数据写到这个文件夹下.
    <defaultCache>: 设置缓存的默认数据过期策略
    <cache> 设定详细的命名缓存的数据过期策略。每个命名缓存代表一个缓存区域

    缓存区域(region):一个具有名称的缓存块,能够给每个缓存块设置不同的缓存策略。假设没有设置不论什么的缓存区域,则全部被缓存的对象,都将使用默认的缓存策略。即:<defaultCache.../>

    Hibernate在不同的缓存区域保存不同的类/集合。

    • 对于类而言,区域的名称是类名。如:com.atguigu.domain.Customer
    • 对于集合而言,区域的名称是类名加属性名。如com.atguigu.domain.Customer.orders


    cache 元素的属性   

    name:设置缓存的名字,它的取值为类的全限定名或类的集合的名字 

    maxInMemory:设置基于内存的缓存中可存放的对象最大数目 

    eternal:设置对象是否为永久的,true表示永只是期,此时将忽略
    timeToIdleSeconds 和 timeToLiveSeconds属性; 默认值是false 

    timeToIdleSeconds:设置对象空暇最长时间,以秒为单位, 超过这个时间,对象过期。

    当对象过期时,EHCache会把它从缓存中清除。假设此值为0,表示对象能够无限期地处于空暇状态。

     

    timeToLiveSeconds:设置对象生存最长时间,超过这个时间,对象过期。

    假设此值为0,表示对象能够无限期地存在于缓存中. 该属性值必须大于或等于 timeToIdleSeconds 属性值 

    overflowToDisk:设置基于内存的缓存中的对象数目达到上限后,是否把溢出的对象写到基于硬盘的缓存中 


    查询缓存

    • 对于常常使用的查询语句, 假设启用了查询缓存, 当第一次运行查询语句时, Hibernate 会把查询结果存放在查询缓存中. 以后再次运行该查询语句时, 仅仅需从缓存中获得查询结果, 从而提高查询性能
    • 查询缓存使用于例如以下场合:
      • 应用程序运行时常常使用查询语句
      • 非常少对与查询语句检索到的数据进行插入, 删除和更新操作
    • 启用查询缓存的步骤
      • 配置二级缓存, 由于查询缓存依赖于二级缓存
      • 在 hibernate 配置文件里启用查询缓存
      • 对于希望启用查询缓存的查询语句, 调用 Query 的 setCacheable() 方法


    时间戳缓存区域(了解)

    时间戳缓存区域存放了对于查询结果相关的表进行插入, 更新或删除操作的时间戳. Hibernate 通过时间戳缓存区域来推断被缓存的查询结果是否过期, 其运行步骤例如以下:

    • T1 时刻运行查询操作, 把查询结果存放在 QueryCache 区域, 记录该区域的时间戳为 T1
    • T2 时刻对查询结果相关的表进行更新操作, Hibernate 把 T2 时刻存放在 UpdateTimestampCache 区域.
    • T3 时刻运行查询结果前, 先比較 QueryCache 区域的时间戳和 UpdateTimestampCache 区域的时间戳, 若 T2 >T1, 那么就丢弃原先存放在 QueryCache 区域的查询结果, 又一次到数据库中查询数据, 再把结果存放到 QueryCache 区域; 若 T2 < T1, 直接从 QueryCache 中获得查询结果

    Query 接口的 iterate() 方法(不建议使用)

    • 同 list() 一样也能运行查询操作
    • list() 方法运行的 SQL 语句包括实体类相应的数据表的全部字段
    • Iterator() 方法运行的SQL 语句中仅包括实体类相应的数据表的 ID 字段
    • 当遍历訪问结果集时, 该方法先到 Session 缓存及二级缓存中查看是否存在特定 OID 的对象, 假设存在, 就直接返回该对象, 假设不存在该对象就通过相应的 SQL Select 语句到数据库中载入特定的实体对象
    • 大多数情况下, 应考虑使用 list() 方法运行查询操作. iterator() 方法仅在满足下面条件的场合, 能够略微提高查询性能:
      • 要查询的数据表中包括大量字段
      • 启用了二级缓存, 且二级缓存中可能已经包括了待查询的对象





    源代码详细解释:

    Department.java

    package com.atguigu.hibernate.entities;
    
    import java.util.HashSet;
    import java.util.Set;
    
    public class Department {
    
    	private Integer id;
    	private String name;
    	
    	private Set<Employee> emps = new HashSet<>();
    
    	public Integer getId() {
    		return id;
    	}
    
    	public void setId(Integer id) {
    		this.id = id;
    	}
    
    	public String getName() {
    		return name;
    	}
    
    	public void setName(String name) {
    		this.name = name;
    	}
    
    	public Set<Employee> getEmps() {
    		return emps;
    	}
    
    	public void setEmps(Set<Employee> emps) {
    		this.emps = emps;
    	}
    
    	@Override
    	public String toString() {
    		return "Department [id=" + id + "]";
    	}
    	
    }
    


    Department.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>
    
        <class name="com.atguigu.hibernate.entities.Department" table="GG_DEPARTMENT">
            
            <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>
            
            <set name="emps" table="GG_EMPLOYEE" inverse="true" lazy="true">
                <key>
                    <column name="DEPT_ID" />
                </key>
                <one-to-many class="com.atguigu.hibernate.entities.Employee" />
            </set>
            
        </class>
    </hibernate-mapping>
    


    Employee.java
    package com.atguigu.hibernate.entities;
    
    public class Employee {
    
    	private Integer id;
    	private String name;
    	private float salary;
    	private String email;
    	
    	private Department dept;
    
    	public Integer getId() {
    		return id;
    	}
    
    	public void setId(Integer id) {
    		this.id = id;
    	}
    
    	public String getName() {
    		return name;
    	}
    
    	public void setName(String name) {
    		this.name = name;
    	}
    
    	public float getSalary() {
    		return salary;
    	}
    
    	public void setSalary(float salary) {
    		this.salary = salary;
    	}
    
    	public String getEmail() {
    		return email;
    	}
    
    	public void setEmail(String email) {
    		this.email = email;
    	}
    
    	public Department getDept() {
    		return dept;
    	}
    
    	public void setDept(Department dept) {
    		this.dept = dept;
    	}
    
    	@Override
    	public String toString() {
    		return "Employee [id=" + id + "]";
    	}
    
    	public Employee(String email, float salary, Department dept) {
    		super();
    		this.salary = salary;
    		this.email = email;
    		this.dept = dept;
    	}
    	
    	public Employee() {
    		// TODO Auto-generated constructor stub
    	}
    	
    }
    


    Employee.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>
    
        <class name="com.atguigu.hibernate.entities.Employee" table="GG_EMPLOYEE">
        	
        	<!--  
        	<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="salary" type="float">
                <column name="SALARY" />
            </property>
            
            <property name="email" type="java.lang.String">
                <column name="EMAIL" />
            </property>
            
            <many-to-one name="dept" class="com.atguigu.hibernate.entities.Department">
                <column name="DEPT_ID" />
            </many-to-one>
            
        </class>
        
        <query name="salaryEmps"><![CDATA[FROM Employee e WHERE e.salary > :minSal AND e.salary < :maxSal]]></query>
        
    </hibernate-mapping>
    


     測试类:
    package com.atguigu.hibernate.test;
    
    import java.sql.Connection;
    import java.sql.SQLException;
    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.Iterator;
    import java.util.LinkedHashSet;
    import java.util.List;
    
    import org.hibernate.Criteria;
    import org.hibernate.Query;
    import org.hibernate.Session;
    import org.hibernate.SessionFactory;
    import org.hibernate.Transaction;
    import org.hibernate.cfg.Configuration;
    import org.hibernate.criterion.Conjunction;
    import org.hibernate.criterion.Disjunction;
    import org.hibernate.criterion.MatchMode;
    import org.hibernate.criterion.Order;
    import org.hibernate.criterion.Projections;
    import org.hibernate.criterion.Restrictions;
    import org.hibernate.jdbc.Work;
    import org.hibernate.service.ServiceRegistry;
    import org.hibernate.service.ServiceRegistryBuilder;
    import org.junit.After;
    import org.junit.Before;
    import org.junit.Test;
    
    import com.atguigu.hibernate.dao.DepartmentDao;
    import com.atguigu.hibernate.entities.Department;
    import com.atguigu.hibernate.entities.Employee;
    import com.atguigu.hibernate.hibernate.HibernateUtils;
    
    public class HibernateTest {
    
    	private SessionFactory sessionFactory;
    	private Session session;
    	private Transaction transaction;
    	
    	@Before
    	public void init(){
    		Configuration configuration = new Configuration().configure();
    		ServiceRegistry serviceRegistry = 
    				new ServiceRegistryBuilder().applySettings(configuration.getProperties())
    				                            .buildServiceRegistry();
    		sessionFactory = configuration.buildSessionFactory(serviceRegistry);
    		
    		session = sessionFactory.openSession();
    		transaction = session.beginTransaction();
    	}
    	
    	@After
    	public void destroy(){
    		transaction.commit();
    		session.close();
    		sessionFactory.close();
    	}
    	
    	@Test
    	public void testBatch(){
    		session.doWork(new Work() {			
    			@Override
    			public void execute(Connection connection) throws SQLException {
    				//通过 JDBC 原生的 API 进行操作, 效率最高, 速度最快!
    			}
    		});
    	}
    	
    	@Test
    	public void testManageSession(){
    		
    		//获取 Session
    		//开启事务
    		Session session = HibernateUtils.getInstance().getSession();
    		System.out.println("-->" + session.hashCode());
    		Transaction transaction = session.beginTransaction();
    		
    		DepartmentDao departmentDao = new DepartmentDao();
    		
    		Department dept = new Department();
    		dept.setName("ATGUIGU");
    		
    		departmentDao.save(dept);
    		departmentDao.save(dept);
    		departmentDao.save(dept);
    		
    		//若 Session 是由 thread 来管理的, 则在提交或回滚事务时, 已经关闭 Session 了. 
    		transaction.commit();
    		System.out.println(session.isOpen()); 
    	}
    	
    	@Test
    	public void testQueryIterate(){
    		Department dept = (Department) session.get(Department.class, 70);
    		System.out.println(dept.getName());
    		System.out.println(dept.getEmps().size()); 
    		
    		Query query = session.createQuery("FROM Employee e WHERE e.dept.id = 80");
    //		List<Employee> emps = query.list();
    //		System.out.println(emps.size()); 
    		
    		Iterator<Employee> empIt = query.iterate();
    		while(empIt.hasNext()){
    			System.out.println(empIt.next().getName()); 
    		}
    	}
    	
    	@Test
    	public void testUpdateTimeStampCache(){
    		Query query = session.createQuery("FROM Employee");
    		query.setCacheable(true);
    		
    		List<Employee> emps = query.list();
    		System.out.println(emps.size());
    		
    		Employee employee = (Employee) session.get(Employee.class, 100);
    		employee.setSalary(30000);
    		
    		emps = query.list();
    		System.out.println(emps.size());
    	}
    	
    	@Test
    	public void testQueryCache(){
    		Query query = session.createQuery("FROM Employee");
    		query.setCacheable(true);
    		
    		List<Employee> emps = query.list();
    		System.out.println(emps.size());
    		
    		emps = query.list();
    		System.out.println(emps.size());
    		
    		Criteria criteria = session.createCriteria(Employee.class);
    		criteria.setCacheable(true);
    	}
    	
    	@Test
    	public void testCollectionSecondLevelCache(){
    		Department dept = (Department) session.get(Department.class, 80);
    		System.out.println(dept.getName());
    		System.out.println(dept.getEmps().size()); 
    		
    		transaction.commit();
    		session.close();
    		
    		session = sessionFactory.openSession();
    		transaction = session.beginTransaction();
    		
    		Department dept2 = (Department) session.get(Department.class, 80);
    		System.out.println(dept2.getName());
    		System.out.println(dept2.getEmps().size()); 
    	}
    	
    	@Test
    	public void testHibernateSecondLevelCache(){
    		Employee employee = (Employee) session.get(Employee.class, 100);
    		System.out.println(employee.getName()); 
    		
    		transaction.commit();
    		session.close();
    		
    		session = sessionFactory.openSession();
    		transaction = session.beginTransaction();
    		
    		Employee employee2 = (Employee) session.get(Employee.class, 100);
    		System.out.println(employee2.getName()); 
    	}
    	
    }
    


    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">
    <hibernate-configuration>
        <session-factory>
        
        	<!-- Hibernate 连接数据库的基本信息 -->
        	<property name="connection.username">scott</property>
        	<property name="connection.password">java</property>
        	<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
        	<property name="connection.url">jdbc:oracle:thin:@localhost:1521:orcl</property>
    
    		<!-- Hibernate 的基本配置 -->
    		<!-- Hibernate 使用的数据库方言 -->
    		<property name="dialect">org.hibernate.dialect.Oracle10gDialect</property>
    	
    		<!-- 运行时是否打印 SQL -->
        	<property name="show_sql">true</property>
        
        	<!-- 运行时是否格式化 SQL -->
        	<property name="format_sql">true</property>
        
        	<!-- 生成数据表的策略 -->
        	<property name="hbm2ddl.auto">update</property>
        	
        	<!-- 设置 Hibernate 的事务隔离级别 -->
        	<property name="connection.isolation">2</property>
        	
        	<!-- 删除对象后, 使其 OID 置为 null -->
        	<property name="use_identifier_rollback">true</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>
        	<property name="c3p0.timeout">2000</property>
        	
        	<property name="c3p0.max_statements">10</property>
        	-->
        	
        	<!-- 设定 JDBC 的 Statement 读取数据的时候每次从数据库中取出的记录条数 -->
        	<property name="hibernate.jdbc.fetch_size">100</property>
        	
        	<!-- 设定对数据库进行批量删除,批量更新和批量插入的时候的批次大小 -->
        	<property name="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>
        	
        	<!-- 配置启用查询缓存 -->
        	<property name="cache.use_query_cache">true</property>
        	
        	<!-- 配置管理 Session 的方式 -->
        	<property name="current_session_context_class">thread</property>
        	
        	<!-- 须要关联的 hibernate 映射文件 .hbm.xml -->
    		<mapping resource="com/atguigu/hibernate/entities/Department.hbm.xml"/>
    		<mapping resource="com/atguigu/hibernate/entities/Employee.hbm.xml"/>
    		
    		<class-cache usage="read-write" class="com.atguigu.hibernate.entities.Employee"/>
    		<class-cache usage="read-write" class="com.atguigu.hibernate.entities.Department"/>
    		<collection-cache usage="read-write" collection="com.atguigu.hibernate.entities.Department.emps"/>
        </session-factory>
    </hibernate-configuration>
    


    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="d:\tempDirectory"/>
    
    
        <!--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"
            />
    
       	<!--  
       		设定详细的命名缓存的数据过期策略。每个命名缓存代表一个缓存区域
       		缓存区域(region):一个具有名称的缓存块,能够给每个缓存块设置不同的缓存策略。

    假设没有设置不论什么的缓存区域,则全部被缓存的对象,都将使用默认的缓存策略。即:<defaultCache.../> Hibernate 在不同的缓存区域保存不同的类/集合。

    对于类而言。区域的名称是类名。如:com.atguigu.domain.Customer 对于集合而言。区域的名称是类名加属性名。如com.atguigu.domain.Customer.orders --> <!-- name: 设置缓存的名字,它的取值为类的全限定名或类的集合的名字 maxElementsInMemory: 设置基于内存的缓存中可存放的对象最大数目 eternal: 设置对象是否为永久的, true表示永只是期, 此时将忽略timeToIdleSeconds 和 timeToLiveSeconds属性; 默认值是false timeToIdleSeconds:设置对象空暇最长时间,以秒为单位, 超过这个时间,对象过期。

    当对象过期时,EHCache会把它从缓存中清除。假设此值为0,表示对象能够无限期地处于空暇状态。 timeToLiveSeconds:设置对象生存最长时间,超过这个时间,对象过期。 假设此值为0,表示对象能够无限期地存在于缓存中. 该属性值必须大于或等于 timeToIdleSeconds 属性值 overflowToDisk:设置基于内存的缓存中的对象数目达到上限后,是否把溢出的对象写到基于硬盘的缓存中 --> <cache name="com.atguigu.hibernate.entities.Employee" maxElementsInMemory="1" eternal="false" timeToIdleSeconds="300" timeToLiveSeconds="600" overflowToDisk="true" /> <cache name="com.atguigu.hibernate.entities.Department.emps" maxElementsInMemory="1000" eternal="true" timeToIdleSeconds="0" timeToLiveSeconds="0" overflowToDisk="false" /> </ehcache>



  • 相关阅读:
    SQL Convert的用法[转]
    C#里巧用DateTime预设一些可选的日期范围(如本年度、本季度、本月等)
    JS 操作IE游览器常用函数:window.external,history,document.execCommand
    sqoop基本应用
    SQLSever图形化界面基本使用
    hadoop 无法退出安全模式 内存够用
    Class<?> b=Class.forName(cName);
    每日学习20210925
    每日学习20210924
    hive 报错:Map local work exhausted memory
  • 原文地址:https://www.cnblogs.com/ldxsuanfa/p/9985966.html
Copyright © 2011-2022 走看看