1. 程式人生 > >hibernate學習筆記第七天

hibernate學習筆記第七天

tca 新的 instance ati 數據傳遞 cas def mls conf

二級緩存配置
1.導入ehcache對應的三個jar包
ehcache/*.jar
2.配置hibernate使用二級緩存
2.1設置當前環境開始二級緩存的使用
<property name="cache.use_second_level_cache">true</property>
2.2設置使用的二級緩存種類
<property name="cache.provider_class">org.hibernate.cache.EhCacheProvider</property>
3.設置加入二級緩存的模型
方法一:
在hbm.xml文件中,設置類和關聯關系對象是否使用二級緩存
<class name="cn.itcast.h3.query.hql.vo.TeacherModel" table="tbl_teacher">
***** <cache usage="read-write"/>
<id name="uuid" column="uuid">
<generator class="native" />
</id>

<property name="teacherName"/>
<property name="nick"/>

<set name="students">
***** <cache usage="read-write"/>
<key column="teacherUuid"/>
<one-to-many class="cn.itcast.h3.query.hql.vo.StudentModel"/>
</set>
</class>
方法二:
類級緩存的配置
<class-cache
usage="read-write"
class="cn.itcast.h3.query.hql.vo.TeacherModel"
/>

模型中的集合緩存的配置
<collection-cache
usage="read-write"
collection="cn.itcast.h3.query.hql.vo.TeacherModel.students"
/>
<class-cache
usage="read-write"
class="cn.itcast.h3.query.hql.vo.StudentModel"
/>
在進行集合緩存配置時,如果使用了某種集合,必須將該集合中的模型也配置到緩存中,
並且是類級緩存
4.二級緩存自身的配置
寫在src目錄下,ehcache.xml
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../config/ehcache.xsd">
<diskStore path="d:\cache-data"/>
<defaultCache
maxElementsInMemory="10"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="1200"
overflowToDisk="true"
maxElementsOnDisk="10000000"
diskPersistent="false"
diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU"
/>
</ehcache>
5.自定義緩存級別設置
6.測試二級緩存的存在性
7.二級緩存中的數據格式
二級緩存中存儲的是加載的數據的散裝格式,散裝數據
讀取二級緩存時,每次創建一個全新的對象,並根據其中OID,查找到對應的屬性數據,進行組裝
8.驗證SQL查詢對緩存的影響
使用SQL查詢的內容會加載到二級緩存中
使用SQL查詢不讀取二級緩存的數據,無論是否提供OID
9.添加的數據是不進入二級緩存的
10.刪除的數據影響二級緩存中的對應數據
11.修改的數據影響二級緩存中的對應數據

關聯集合數據二級緩存操作
1.關聯集合數據也進入二級緩存
2.關聯集合緩存裏面存儲的是每個對象的OID,而不是所有的數據,因此當類級緩存沒有存儲數據時
關聯集合緩存中僅存OID,再次獲取時,必須重新按照OID查找數據

Hibernate的更新操作
當執行DML格式更新數據庫,而不是使用常規的更新時,此時可能影響的數據量過多
當再次讀取二級緩存時,無論讀取曾經修改過的模型的任意數據,全部重新加載
Query q = s.createQuery("update TeacherModel set teacherName=:teacherName where uuid = :uuid");
q.setString("teacherName", "測試更新1");
q.setLong("uuid", 4L);
q.executeUpdate();

查詢緩存
查詢緩存是將每次查詢的SQL語句與查詢的結果全部保存起來,一對一
查詢緩存開啟方式
cfg.xml
<property name="cache.use_query_cache">true</property>
針對某一次的查詢設定是否使用查詢緩存
Query q = ....
q.setCacheable(true);

Session管理
表現層
頁面數據收集,將數據封裝後,傳遞給邏輯層
邏輯層
組合業務功能,將數據傳遞給數據層
void 轉賬(){
事務開啟
A轉賬到銀行總賬號 update
銀行總賬號轉賬到B update
事務提交
}
數據層
數據處理
update(){}

解決方案:
針對一次請求,創建一個Session對象
使用線程綁定Session就可以解決上述問題
1.配置cfg.xml,設置開啟線程綁定Session
<property name="current_session_context_class">thread</property>
2.獲取Session對象
Session s = HibernateUtil.getSf().getCurrentSession();

hibernate學習筆記第七天