Hibernate緩衝,hibernate緩衝機制

來源:互聯網
上載者:User

Hibernate緩衝,hibernate緩衝機制
一、Hibernate緩衝概述

Hibernate中提供兩個層級的緩衝,一級緩衝和二級緩衝。

1.一級緩衝是Session層級的緩衝,它屬於事物範圍的緩衝,一級緩衝有hibernate進行管理。

2.二級緩衝是sessionFactory層級的緩衝,它屬於進程範圍的緩衝,二級緩衝又可分為"內建緩衝"和"外置緩衝",內建緩衝:是hibernate在建立sessionFactory時會載入.hbn.xml檔案並會在記憶體中初始化一些預設的sql語句,該內建緩衝是唯讀;外置緩衝(二級緩衝),預設sessionFactory不會啟動這個快取區外掛程式,外置緩衝中的資料是資料庫中資料的複製,儲存的物理介質可以是記憶體或者硬碟。

二、Hibernate一級緩衝

session的緩衝有兩大作用:

1.減少訪問資料庫的頻率。

2.保證資料庫中的相關記錄與緩衝中的相關對象保持一致。

Session根據髒對象的最新屬性執行相關SQL語句,從而保證了資料庫中的相關記錄與緩衝中的響應對象的同步,預設在如下時間點,session會清理緩衝:

1.應用程式調用Transaction的commit()方法時,commit()會先清理緩衝,再向資料庫提交事務。

2.應用程式執行一些查詢操作,緩衝中的持久化對象的屬性發生變化時。

3.顯式調用Session的flush()方法。

Session提供了兩個管理緩衝的方法:

1.evict(Object obj);從緩衝中清除特定持久化對象。

2.clear();清空緩衝中,所有持久化對象。

三、Hibernate二級緩衝

1. 使用 Hibernate 二級緩衝的步驟:

1). 加入二級快取區外掛程式的 jar 包及設定檔:

I. 複製 \hibernate-release-4.2.4.Final\lib\optional\ehcache\*.jar 到當前 Hibrenate 應用的類路徑下.
II. 複製 hibernate-release-4.2.4.Final\project\etc\ehcachexml 到當前 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) 方法
@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);
}
III. 查詢快取依賴於二級緩衝(使用查詢快取的前提是配置hibernate二級緩衝)

樣本:

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;}@Overridepublic 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;}@Overridepublic 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>

  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>

  ecache.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>

  二級緩衝的查詢快取的使用:

@Testpublic 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);}

  二級查詢快取的最佳化:

@Testpublic 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");/** * 使用query.list()方法會查詢Employee所有欄位,並用反射機制組裝成List<Employee> 對象 *///List<Employee> emps = query.list();//System.out.println(emps.size()); /** * query.iterator()只查id欄位,根據id從二級緩衝中找對象,如果二級中有則組裝,二級緩衝沒有再從資料庫中找 * 不用在記憶體中產生一批Employee對象裝配集合了, * 使用這種方法需要: * 1.查詢的資料表中包含大量的欄位 * 2.開啟二級緩衝,並且二級緩衝中很可能包含了要查詢的對象,如果不包含會很可怕,會根據id從資料庫中查詢每一個對象 */Iterator<Employee> empIt = query.iterate();while(empIt.hasNext()){System.out.println(empIt.next().getName()); }}

  時間戳記快取區域說明:

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);// 會先執行select語句,再執行update語句,再執行select語句/** * 時間戳記快取區域存放了對於查詢結果相關的表進行插入, 更新或刪除操作的時間戳記.   * Hibernate 通過時間戳記快取區域來判斷被緩衝的查詢結果是否到期, 其運行過程如下: * T1 時刻執行查詢操作, 把查詢結果存放在 QueryCache 地區, 記錄該地區的時間戳記為 T1 * T2 時刻對查詢結果相關的表進行更新操作, Hibernate 把 T2 時刻存放在 UpdateTimestampCache 地區. * T3 時刻執行查詢結果前, 先比較 QueryCache 地區的時間戳記和 UpdateTimestampCache 地區的時間戳記,  * 若 T2 >T1, 那麼就丟棄原先存放在 QueryCache 地區的查詢結果, 重新到資料庫中查詢資料, 再把結果存放到 QueryCache 地區;  * 若 T2 < T1, 直接從 QueryCache 中獲得查詢結果 */emps = query.list();System.out.println(emps.size());}

  

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.