鍍金池/ 教程/ Java/ Hibernate二級(jí)緩存
Hibernate繼承映射
Hibernate每個(gè)子類(lèi)一張表(使用XML文件)實(shí)例
Hibernate快速入門(mén)
Hibernate使用注釋
Hibernate使用xml文件的每個(gè)類(lèi)層次一張表
Hibernate命名查詢(xún)
Hibernate每個(gè)層次類(lèi)一張表(使用注釋?zhuān)?/span>
Hibernate組件映射
Hibernate事務(wù)管理
Hibernate二級(jí)緩存
集合映射Set(使用xml文件)
Hibernate每個(gè)具體類(lèi)一張表映射(使用XML)
集合映射中的映射列表(使用xml文件)
Hibernate使用Log4j日志記錄(使用properties文件)
Hibernate集合映射
集合Map映射(使用xml文件)
集合Set映射一對(duì)多(使用xml文件)
Hibernate查詢(xún)語(yǔ)言(HQL)
Hibernate入門(mén)程序
Hibernate標(biāo)準(zhǔn)查詢(xún)語(yǔ)言
Hibernate使用Log4j日志記錄(使用xml文件)
Hibernate教程
Hibernate體系結(jié)構(gòu)
Hibernate生成器類(lèi)
Hibernate通過(guò)many-to-one元素的一對(duì)一映射
集合Map多對(duì)多映射(使用xml文件)
Web應(yīng)用程序使用Hibernate
Hibernate一對(duì)多映射列表實(shí)例(使用xml文件)
Hibernate通過(guò)one-to-one元素的一對(duì)一映射
Hibernate每個(gè)子類(lèi)一張表(使用注釋?zhuān)?shí)例
集合映射中的映射包(使用xml文件)
通過(guò)Bag一對(duì)多映射示例(使用xml文件)
Hibernate緩存
Hibernate每個(gè)具體類(lèi)一張表映射(使用注釋?zhuān)?/span>

Hibernate二級(jí)緩存

Hibernate第二級(jí)緩存是會(huì)話工廠的所有會(huì)話(Session)對(duì)象所使用的公共緩存。 如果您有來(lái)自會(huì)話工廠的多個(gè)會(huì)話(Session)對(duì)象,就可以操作會(huì)話工廠中的第二級(jí)緩存的數(shù)據(jù)。

SessionFactory類(lèi)用于保存二級(jí)緩存數(shù)據(jù)。 它是所有會(huì)話對(duì)象的全局,默認(rèn)情況下是不啟用的。

不同廠商提供了二級(jí)緩存的實(shí)現(xiàn)。

  1. EH二級(jí)緩存
  2. OS二級(jí)緩存
  3. Swarm二級(jí)緩存
  4. JBoss二級(jí)緩存

每個(gè)實(shí)現(xiàn)提供不同的緩存使用功能。 有四種方法可以使用二級(jí)緩存。

  1. 只讀:緩存將適用于只讀操作。
  2. 非嚴(yán)格讀寫(xiě):緩存可用于讀寫(xiě),但一次只能讀寫(xiě)。
  3. 讀寫(xiě):緩存將用于讀寫(xiě),可以同時(shí)使用。
  4. 事務(wù)處理:緩存將用于事務(wù)處理。
    緩存使用屬性可以應(yīng)用于hbm.xml文件中的類(lèi)或集合級(jí)別。 下面給出了定義緩存使用情況的例子:
    <cache usage="read-only" />
    
    下面來(lái)看看看二級(jí)緩存實(shí)現(xiàn)和緩存使用情況。
實(shí)現(xiàn) 只讀 非限制讀寫(xiě) 讀寫(xiě) 操作
EH二級(jí)緩存 Yes Yes Yes No
OS二級(jí)緩存 Yes Yes Yes No
Swarm二級(jí)緩存 Yes Yes No No
JBoss二級(jí)緩存 No No No Yes

使用EH緩存的二級(jí)緩存示例的額外步驟

1)在hibernate.cfg.xml文件中添加2個(gè)配置設(shè)置

<property name="cache.provider_class">org.hibernate.cache.EhCacheProvider</property>  
<property name="hibernate.cache.use_second_level_cache">true</property>

2) 在hbm文件中添加緩存使用情況設(shè)置

<cache usage="read-only" />

3) 創(chuàng)建ehcache.xml文件

<?xml version="1.0"?>  
<ehcache>  
    <defaultCache maxElementsInMemory="100"  eternal="true"/>  
</ehcache>

Hibernate二級(jí)緩存示例

要通過(guò)下面示例了解二級(jí)緩存,我們需要?jiǎng)?chuàng)建一個(gè)Java項(xiàng)目:secondlevel, 其完整的目錄結(jié)構(gòu)如下所示 -

創(chuàng)建以下頁(yè)面:

  1. Employee.java
  2. employee.hbm.xml
  3. hibernate.cfg.xml
  4. ehcache.xml
  5. MainTest.java

注意:在這里,我們假設(shè),在MySQL數(shù)據(jù)庫(kù)中有一個(gè)emp_cache2表并包含一些記錄。

文件: Employee.java

package com.yiibai;

public class Employee {
    private int id;
    private String name;
    private float salary;

    public Employee() {
        super();
    }

    public Employee(String name, float salary) {
        super();
        this.name = name;
        this.salary = salary;
    }

    public int getId() {
        return id;
    }

    public void setId(int 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;
    }

}

文件: employee.hbm.xml

<?xml version='1.0' encoding='UTF-8'?>
<!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.yiibai.Employee" table="emp_cache">
        <cache usage="read-only" />
        <id name="id">
            <generator class="native"></generator>
        </id>
        <property name="name"></property>
        <property name="salary"></property>
    </class>

</hibernate-mapping>

在這里,我們使用只讀(read-only)高速緩存來(lái)使用該類(lèi)。緩存使用情況也可用于集合。

文件: hibernate.cfg.xml



要實(shí)現(xiàn)二級(jí)緩存,我們需要在配置文件中定義cache.provider_class屬性。

文件:ehcache.xml

<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:noNamespaceSchemaLocation="ehcache.xsd" updateCheck="true"
    monitoring="autodetect" dynamicConfig="true">

    <diskStore path="java.io.tmpdir/ehcache" />

    <defaultCache maxEntriesLocalHeap="10000" eternal="false"
        timeToIdleSeconds="120" timeToLiveSeconds="120" diskSpoolBufferSizeMB="30"
        maxEntriesLocalDisk="10000000" diskExpiryThreadIntervalSeconds="120"
        memoryStoreEvictionPolicy="LRU" statistics="true">
        <persistence strategy="localTempSwap" />
    </defaultCache>

    <cache name="org.hibernate.cache.internal.StandardQueryCache"
        maxEntriesLocalHeap="5" eternal="false" timeToLiveSeconds="120">
        <persistence strategy="localTempSwap" />
    </cache>

    <cache name="org.hibernate.cache.spi.UpdateTimestampsCache"
        maxEntriesLocalHeap="5000" eternal="true">
        <persistence strategy="localTempSwap" />
    </cache>
    <cache name="com.yiibai.Employee" maxElementsInMemory="100"
        eternal="false" timeToIdleSeconds="5" timeToLiveSeconds="200" />
</ehcache>

我們需要?jiǎng)?chuàng)建ehcache.xml文件來(lái)定義緩存屬性。

defaultCache將用于所有持久化類(lèi)。 我們還可以通過(guò)使用 cache 元素來(lái)明確定義持久化類(lèi)。
eternal 如果我們指定eternal =“true”,則不需要定義timeToIdleSecondstimeToLiveSeconds屬性,因?yàn)樗鼘⒂?code>hibernate內(nèi)部處理。 指定eternal =“false”給程序員控制,但是我們需要定義timeToIdleSecondstimeToLiveSeconds屬性
timeToIdleSeconds它定義了二級(jí)緩存中對(duì)象可以空閑多少秒。
timeToLiveSeconds它定義了在第二級(jí)緩存中對(duì)象可以存儲(chǔ)多少秒,無(wú)論它是否空閑。

文件:MainTest.java

package com.yiibai;

import org.hibernate.*;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.*;
import org.hibernate.stat.Statistics;

public class MainTest {
    public static void main(String[] args) {
        // 在5.1.0版本匯總,hibernate則采用如下新方式獲取:
        // 1. 配置類(lèi)型安全的準(zhǔn)服務(wù)注冊(cè)類(lèi),這是當(dāng)前應(yīng)用的單例對(duì)象,不作修改,所以聲明為final
        // 在configure("cfg/hibernate.cfg.xml")方法中,如果不指定資源路徑,默認(rèn)在類(lèi)路徑下尋找名為hibernate.cfg.xml的文件
        final StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
                .configure("hibernate.cfg.xml").build();
        // 2. 根據(jù)服務(wù)注冊(cè)類(lèi)創(chuàng)建一個(gè)元數(shù)據(jù)資源集,同時(shí)構(gòu)建元數(shù)據(jù)并生成應(yīng)用一般唯一的的session工廠
        SessionFactory sessionFactory = new MetadataSources(registry)
                .buildMetadata().buildSessionFactory();

        /**** 上面是配置準(zhǔn)備,下面開(kāi)始我們的數(shù)據(jù)庫(kù)操作 ******/
        Session session = sessionFactory.openSession();// 從會(huì)話工廠獲取一個(gè)session

        // creating transaction object
        Transaction tx = session.beginTransaction();

        Statistics stats = sessionFactory.getStatistics();
        System.out.println("Stats enabled="+stats.isStatisticsEnabled());

        stats.setStatisticsEnabled(true);
        System.out.println("Stats enabled="+stats.isStatisticsEnabled());

        session.save(new Employee("蘇小牛", 12000));
        session.save(new Employee("庫(kù)日天", 19000));

        Session session1 = sessionFactory.openSession();
        Employee emp1 = (Employee) session1.load(Employee.class, 1);
        System.out.println(emp1.getId() + " " + emp1.getName() + " "
                + emp1.getSalary());
        session1.close();

        //再次查詢(xún)ID=1的員工信息,因?yàn)槭褂昧司彺?,這里不會(huì)再發(fā)出查詢(xún)語(yǔ)句...
        Session session11 = sessionFactory.openSession();
        Employee emp11 = (Employee) session11.load(Employee.class, 1);
        System.out.println(emp11.getId() + " " + emp11.getName() + " "
                + emp11.getSalary());
        session11.close();


        Session session2 = sessionFactory.openSession();
        Employee emp2 = (Employee) session2.load(Employee.class, 2);
        System.out.println(emp2.getId() + " " + emp2.getName() + " "
                + emp2.getSalary());
        session2.close();

        tx.commit();
        session.close();
        sessionFactory.close();
    }
}

我們可以看到,hibernate不會(huì)發(fā)出兩次查詢(xún)。 如果不使用二級(jí)緩存,hibernate將會(huì)發(fā)出兩次查詢(xún),因?yàn)檫@兩個(gè)查詢(xún)都使用不同的會(huì)話對(duì)象。

運(yùn)行實(shí)例

首先運(yùn)行 MainTest.java 插入數(shù)據(jù),然后再讀取數(shù)據(jù)。
執(zhí)行 MainTest.java 得到以下結(jié)果,

log4j:WARN No appenders could be found for logger (org.jboss.logging).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
Wed Mar 29 21:38:06 CST 2017 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
Stats enabled=false
Stats enabled=true
Hibernate: insert into emp_cache (name, salary) values (?, ?)
Hibernate: insert into emp_cache (name, salary) values (?, ?)
Hibernate: select employee0_.id as id1_0_0_, employee0_.name as name2_0_0_, employee0_.salary as salary3_0_0_ from emp_cache employee0_ where employee0_.id=?
Wed Mar 29 21:38:08 CST 2017 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
1 蘇小牛 12000.0
1 蘇小牛 12000.0
Hibernate: select employee0_.id as id1_0_0_, employee0_.name as name2_0_0_, employee0_.salary as salary3_0_0_ from emp_cache employee0_ where employee0_.id=?
2 庫(kù)日天 19000.0

上一篇:Hibernate繼承映射下一篇:Hibernate教程