您好,登錄后才能下訂單哦!
1、二級緩存的知識
Hibernate提供的緩存:有一級緩存、二級緩存。 目的是為了減少對數據庫的訪問次數,提升程序執行效率!
一級緩存:基于Session的緩存,緩存內容只在當前session有效,session關閉,緩存內容失效!
特點:作用范圍較小! 緩存的時間短。緩存效果不明顯。
二級緩存:
Hibernate提供了基于應用程序級別的緩存, 可以跨多個session,即不同的session都可以訪問緩存數據。 這個緩存也叫二級緩存。
Hibernate提供的二級緩存有默認的實現,且是一種可插配的緩存框架!如果用戶想用二級緩存,只需要在hibernate.cfg.xml中配置即可;不想用,直接移除,不影響代碼。
如果用戶覺得hibernate提供的框架不好用,可以換其他的緩存框架或自己實現緩存框架都可以。
下面的配置位于%hibernate%/project/etc/hibernate.properties中
########################## ### Second-level Cache ### ########################## ## disable the second-level cache 二級緩存默認不開啟,需要手動開啟 #hibernate.cache.use_second_level_cache false ## enable the query cache #hibernate.cache.use_query_cache true 開啟查詢緩存 ## choose a cache implementation 二級緩存框架的實現 #hibernate.cache.provider_class org.hibernate.cache.EhCacheProvider #hibernate.cache.provider_class org.hibernate.cache.EmptyCacheProvider hibernate.cache.provider_class org.hibernate.cache.HashtableCacheProvider #hibernate.cache.provider_class org.hibernate.cache.TreeCacheProvider #hibernate.cache.provider_class org.hibernate.cache.OSCacheProvider #hibernate.cache.provider_class org.hibernate.cache.SwarmCacheProvider
緩存的并發策略
<class-cache usage="read-only"/> 放入二級緩存的對象,只讀; <class-cache usage="nonstrict-read-write"/> 非嚴格的讀寫 <class-cache usage="read-write"/> 讀寫; 放入二級緩存的對象可以讀、寫; <class-cache usage="transactional"/> (基于事務的策略)
2、使用二級緩存
二級緩存,使用步驟
1)開啟二級緩存
<property name="hibernate.cache.use_second_level_cache">true</property>
2)指定緩存框架
<property name="hibernate.cache.provider_class">org.hibernate.cache.HashtableCacheProvider</property>
3)指定那些類加入二級緩存
<!-- 指定哪一些類,需要加入二級緩存 --> <class-cache usage="read-write" class="com.rk.hibernate.cache.Department"/> <class-cache usage="read-write" class="com.rk.hibernate.cache.Employee"/> <!-- 集合緩存[集合緩存的元素對象,也加加入二級緩存] --> <collection-cache usage="read-write" collection="com.rk.hibernate.cache.Department.emps"/>
4)測試二級緩存!
示例代碼和配置
hibernate.cfg.xml
<!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節點代表一個數據庫 --> <session-factory> <!-- 1. 數據庫連接配置 --> <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> <property name="hibernate.connection.url">jdbc:mysql:///test</property> <property name="hibernate.connection.username">root</property> <property name="hibernate.connection.password">root</property> <!-- 數據庫方言配置, hibernate在運行的時候,會根據不同的方言生成符合當前數據庫語法的sql --> <property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property> <!-- 2. 其他相關配置 --> <!-- 2.1 顯示hibernate在運行時候執行的sql語句 --> <property name="hibernate.show_sql">true</property> <!-- 2.2 格式化sql --> <property name="hibernate.format_sql">false</property> <!-- 2.3 自動建表 --> <property name="hibernate.hbm2ddl.auto">update</property> <!--****************** 【二級緩存配置】****************** --> <!-- a. 開啟二級緩存 --> <property name="hibernate.cache.use_second_level_cache">true</property> <!-- b. 指定使用哪一個緩存框架(默認提供的) --> <property name="hibernate.cache.provider_class">org.hibernate.cache.HashtableCacheProvider</property> <!-- 開啟查詢緩存 --> <property name="hibernate.cache.use_query_cache">true</property> <!-- c. 指定哪一些類,需要加入二級緩存 --> <class-cache usage="read-write" class="com.rk.hibernate.cache.Department"/> <class-cache usage="read-write" class="com.rk.hibernate.cache.Employee"/> <!-- 集合緩存[集合緩存的元素對象,也加加入二級緩存] --> <collection-cache usage="read-write" collection="com.rk.hibernate.cache.Department.emps"/> </session-factory> </hibernate-configuration>
Department.java
package com.rk.hibernate.cache; import java.util.Set; public class Department { private int deptId; private String deptName; private Set<Employee> emps; private int version; public int getVersion() { return version; } public void setVersion(int version) { this.version = version; } public int getDeptId() { return deptId; } public void setDeptId(int deptId) { this.deptId = deptId; } public String getDeptName() { return deptName; } public void setDeptName(String deptName) { this.deptName = deptName; } public Set<Employee> getEmps() { return emps; } public void setEmps(Set<Employee> emps) { this.emps = emps; } @Override public String toString() { return "Department [deptId=" + deptId + ", deptName=" + deptName + "]"; } }
Department.hbm.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="com.rk.hibernate.cache" auto-import="true"> <class name="Department" table="T_Department"> <!-- <cache usage="read-only"/> --> <id name="deptId" column="id"> <generator class="native"></generator> </id> <version name="version" column="dept_version"></version> <property name="deptName" column="name" type="string"></property> <set name="emps" table="T_Employee"> <!-- <cache usage="read-only"/> --> <key column="deptId"></key> <one-to-many class="Employee"/> </set> </class> </hibernate-mapping>
Employee.java
package com.rk.hibernate.cache; public class Employee { private int empId; private String empName; private int salary; private Department dept; private int version; public int getVersion() { return version; } public void setVersion(int version) { this.version = version; } public int getEmpId() { return empId; } public void setEmpId(int empId) { this.empId = empId; } public String getEmpName() { return empName; } public void setEmpName(String empName) { this.empName = empName; } public int getSalary() { return salary; } public void setSalary(int salary) { this.salary = salary; } public Department getDept() { return dept; } public void setDept(Department dept) { this.dept = dept; } @Override public String toString() { return "Employee [empId=" + empId + ", empName=" + empName + ", salary=" + salary + "]"; } }
Employee.hbm.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="com.rk.hibernate.cache" auto-import="true"> <class name="Employee" table="T_Employee"> <!-- <cache usage="read-only"/> --> <id name="empId" column="id"> <generator class="native"></generator> </id> <version name="version" column="emp_version"></version> <property name="empName" column="name" type="string"></property> <property name="salary" column="salary" type="int"></property> <many-to-one name="dept" column="deptId" class="Department"></many-to-one> </class> </hibernate-mapping>
App.java
package com.rk.hibernate.cache; import java.util.Iterator; import java.util.List; import java.util.Set; import org.hibernate.Query; import org.hibernate.SQLQuery; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; import org.junit.Test; public class App { private static SessionFactory sf; static { sf = new Configuration() .configure() .addClass(Department.class) .addClass(Employee.class) .buildSessionFactory(); } // 1. 測試二級緩存的使用 //思路:sesion本身提供了一級緩存,它是mandatory,不能關閉 //二級緩存,是optional,通過配置文件可以開啟,可以關閉。 //如果不開啟二級緩存,兩個session查詢同一個id的數據,會發送兩個SQL語句 //如果開啟二級緩存,兩個session查詢同一個id的數據,會發送一條SQL語句 //通過開啟和關閉二級緩存,來查看執行的SQL數目 @Test public void testSecondLevelCache() { //第1次查詢,第一個session Session session1 = sf.openSession(); session1.beginTransaction(); Department dept1 = (Department) session1.get(Department.class, 3); Set<Employee> emps1 = dept1.getEmps(); System.out.println(dept1); System.out.println(emps1); session1.getTransaction().commit(); session1.close(); System.out.println("-------------------------------"); //第2次查詢,第二個session Session session2 = sf.openSession(); session2.beginTransaction(); Department dept2 = (Department) session2.get(Department.class, 3); Set<Employee> emps2 = dept2.getEmps(); System.out.println(dept2); System.out.println(emps2); session2.getTransaction().commit(); session2.close(); } @Test public void testQueryCache() { // 第1次查詢,第一個session Session session1 = sf.openSession(); session1.beginTransaction(); // HQL查詢 【setCacheable 指定從二級緩存找,或者是放入二級緩存】 Query q1 = session1.createQuery("from Department").setCacheable(true); List<Department> list1 = q1.list(); System.out.println(list1); session1.getTransaction().commit(); session1.close(); System.out.println("-------------------------------"); // 第2次查詢,第二個session Session session2 = sf.openSession(); session2.beginTransaction(); // HQL查詢 【setCacheable 指定從二級緩存找,或者是放入二級緩存】 Query q2 = session2.createQuery("from Department").setCacheable(true); List<Department> list2 = q2.list(); System.out.println(list2); session2.getTransaction().commit(); session2.close(); } }
當我們開啟二級緩存后,例如在上面的testSecondLevelCache()方法中,第一次從Session讀取數據后,會存儲在二級緩存上;第二次打開Session,程序再進行相同查詢,就不需要再發送SQL語句,因為它會從二級緩存中讀取數據。
有一點需要注意:如果二級緩存中沒有數據,第一次開啟Session讀取數據,并調用session.clear()方法,再讀取數據,會發送兩次SQL語句。
@Test public void test1() { // 第1次查詢,第一個session Session session1 = sf.openSession(); session1.beginTransaction(); Department dept1 = (Department) session1.get(Department.class, 2); System.out.println(dept1); System.out.println(dept1.getEmps()); session1.clear(); dept1 = (Department) session1.get(Department.class, 2); System.out.println(dept1); System.out.println(dept1.getEmps()); session1.getTransaction().commit(); session1.close(); }
結果如下:
Hibernate: select department0_.id as id0_0_, department0_.dept_version as dept2_0_0_, department0_.name as name0_0_ from T_Department department0_ where department0_.id=? Department [deptId=2, deptName=woqu] Hibernate: select emps0_.deptId as deptId0_1_, emps0_.id as id1_, emps0_.id as id1_0_, emps0_.emp_version as emp2_1_0_, emps0_.name as name1_0_, emps0_.salary as salary1_0_, emps0_.deptId as deptId1_0_ from T_Employee emps0_ where emps0_.deptId=? [Employee [empId=3, empName=TO_T_, salary=4]] Hibernate: select department0_.id as id0_0_, department0_.dept_version as dept2_0_0_, department0_.name as name0_0_ from T_Department department0_ where department0_.id=? Department [deptId=2, deptName=woqu] Hibernate: select emps0_.deptId as deptId0_1_, emps0_.id as id1_, emps0_.id as id1_0_, emps0_.emp_version as emp2_1_0_, emps0_.name as name1_0_, emps0_.salary as salary1_0_, emps0_.deptId as deptId1_0_ from T_Employee emps0_ where emps0_.deptId=? [Employee [empId=3, empName=TO_T_, salary=4]]
如果二級緩存中已經存在數據,第二次開啟Session,調用session.clear(),再讀取數據,并不會發送SQL語句。
@Test public void test1() { Session session2 = sf.openSession(); session2.beginTransaction(); Department dept2 = (Department) session2.get(Department.class, 2); System.out.println(dept2); System.out.println(dept2.getEmps()); session2.getTransaction().commit(); session2.close(); System.out.println("-------------------------------"); // 第1次查詢,第一個session Session session1 = sf.openSession(); session1.beginTransaction(); Department dept1 = (Department) session1.get(Department.class, 2); System.out.println(dept1); System.out.println(dept1.getEmps()); session1.clear(); dept1 = (Department) session1.get(Department.class, 2); System.out.println(dept1); System.out.println(dept1.getEmps()); session1.getTransaction().commit(); session1.close(); System.out.println("-------------------------------"); }
結果如下:
Hibernate: select department0_.id as id0_0_, department0_.dept_version as dept2_0_0_, department0_.name as name0_0_ from T_Department department0_ where department0_.id=? Department [deptId=2, deptName=woqu] Hibernate: select emps0_.deptId as deptId0_1_, emps0_.id as id1_, emps0_.id as id1_0_, emps0_.emp_version as emp2_1_0_, emps0_.name as name1_0_, emps0_.salary as salary1_0_, emps0_.deptId as deptId1_0_ from T_Employee emps0_ where emps0_.deptId=? [Employee [empId=3, empName=TO_T_, salary=4]] ------------------------------- Department [deptId=2, deptName=woqu] [Employee [empId=3, empName=TO_T_, salary=4]] Department [deptId=2, deptName=woqu] [Employee [empId=3, empName=TO_T_, salary=4]] -------------------------------
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。