JavaEE笔记(五)
version 必須配置在id后面
緩存文件在映射文件后面
一級緩存:session回話級別
Session緩存的作用
(1)減少訪問數據庫的頻率。應用程序從內存中讀取持久化對象的速度顯然比到數據庫中查詢數據的速度快多了,因此Session的緩存可以提高數據訪問的性能。
(2)保證緩存中的對象與數據庫中的相關記錄保持同步。當緩存中持久化對象的狀態發生了變化,Session并不會立即執行相關的SQL語句,這使得Session能夠把幾條相關的SQL語句合并為一條SQL語句,以便減少訪問數據庫的次數,從而提高應用程序的性能。
Session的清理緩存
清理緩存是指按照緩存中對象的狀態的變化來同步更新數據庫,下面我們還是具體來看一段代碼:以下程序代碼對Customer的name屬性修改了兩次:
tx = session.beginTransaction(); Customer customer=(Customer)session.load(Customer.class, new Long(1)); customer.setName("Jack"); customer.setName("Mike"); tx.commit();當Session清理緩存時,只需執行一條update語句:
update CUSTOMERS set NAME= ‘Mike’…… where ID=1;其實第一次調用setName是無意義的,完全可以省略掉。
Session緩存在什么時候才清理呢?我們來看一下:
Session會在下面的時間點清理緩存:
1. 當應用程序調用org.hibernate.Transaction的commit()方法的時候,commit()方法先清理緩存,然后再向數據庫提交事務。
2. 當應用程序顯式調用Session的flush()方法的時候,其實這個方法我們幾乎很少用到,因為我們一般都是在完成一個事務才去清理緩存,提交數據更改,這樣我們直接提交事務就可以。
二級緩存:sessionFactory工廠級別
二級緩存插件EHCache的 jar 包及配置文件
在hibernate.cfg.xml文件中進行配置
<!-- 配置啟用 hibernate 的二級緩存 --> <property name="cache.use_second_level_cache">true</property> <!-- 配置hibernate二級緩存使用的產品 --> <property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property> <!-- 配置對哪些類使用 hibernate 的二級緩存 --> <class-cache usage="read-write" class="com.atguigu.hibernate.entities.Employee"/>集合級別的二級緩存的配置
<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> <!-- 注意: 還需要配置集合中的元素對應的持久化類也使用二級緩存! 否則將會多出 n 條 SQL 語句. --> <class-cache usage="read-write" class="com.atguigu.hibernate.entities.Employee"/>二級緩存的清除
1:調用evict()方法;
2:關閉SessionFacotry;
轉載于:https://www.cnblogs.com/HackerBlog/p/6102706.html
總結
以上是生活随笔為你收集整理的JavaEE笔记(五)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: zend studio中ctrl+鼠标左
- 下一篇: 跨域请求,关于后端session会话丢失