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)。
每個(gè)實(shí)現(xiàn)提供不同的緩存使用功能。 有四種方法可以使用二級(jí)緩存。
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>
要通過(guò)下面示例了解二級(jí)緩存,我們需要?jiǎng)?chuàng)建一個(gè)Java項(xiàng)目:secondlevel
, 其完整的目錄結(jié)構(gòu)如下所示 -
創(chuàng)建以下頁(yè)面:
注意:在這里,我們假設(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”
,則不需要定義timeToIdleSeconds
和timeToLiveSeconds
屬性,因?yàn)樗鼘⒂?code>hibernate內(nèi)部處理。 指定eternal =“false”
給程序員控制,但是我們需要定義timeToIdleSeconds
和timeToLiveSeconds
屬性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)行 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