2013-06-30 28 views
1

我正在使用Hibernate 3.2.5。一對多協會的二級緩存

我有DepartmentTraining表之間的一對多關係。啓用了二級緩存(使用EHCache),並且在dept.cfg.xml和用於緩存數據的`training.hbm.xml文件中都創建了以下條目。

<cache usage="read-only" /> 

問題描述

這是第一次,DB命中是獲得兩個DeptTraining記錄完成的。第二次,從緩存中獲取Department數據,但爲了獲取Training數據,數據庫命中再次完成 - 爲什麼?我希望這個Training數據也可以從緩存中獲取,而不是每次都打到數據庫。

這是Dept.java文件:

private int deptId; 
private String deptName; 
private Map trainingDetails; 

我所提到的dept.hbm.xml文件的映射如下所示:

//Mappings between POJO and DB Table 
<map name="trainingDetails" inverse="false" cascade="delete" lazy="false"> 
     <key column="DEPT_ID"></key>   
     <map-key formula="ID" type="integer"></map-key> 
     <one-to-many class="com.model.Training"/>   
</map> 

這是代碼我嘗試過:

SessionFactory sf = new Configuration().configure("trial.cfg.xml").buildSessionFactory(); 
    Session session = sf.openSession(); 

    Dept department = (Dept)session.load(Dept.class, 1); 
    //Some business related operations 
    session.flush(); 
    session.close(); 
      //Some operations 
      Session session1 = sf.openSession();   
    Dept department1 = (Dept)session1.load(Dept.class, 1); 
    //Here I can see in the console the query for fetching the 
    //training details for the department is getting executed again 
    //but the Department details is getting fetched from the Cache - WHY? 
    //I want the Training details also to be fetched from the cache. 
    session1.flush(); 
    session1.close(); 

請讓我知道我缺少什麼以及如何解決這個問題。

回答

4

如果你告訴Hibernate的緩存Department實體二級緩存,每個緩存Department它將存儲值的deptIddeptName領域。但是,它不會默認存儲trainingDetails字段的內容。如果從第二級緩存讀取Department,並且應用程序需要訪問members字段,Hibernate將轉到數據庫以確定該集合的當前成員。

如果你想Hibernate的緩存成員字段的內容,你需要告訴它通過增加cache元素的members聲明這樣做:

//Mappings between POJO and DB Table 
<map name="trainingDetails" inverse="false" cascade="delete" lazy="false"> 
     <!-- Cache the ids of entities are members of this collection --> 
     <cache usage="read-only" /> 
     <key column="DEPT_ID"></key>   
     <map-key formula="ID" type="integer"></map-key> 
     <one-to-many class="com.model.Training"/>   
</map> 
+0

謝謝,這解決了我的問題,很好的解釋:) – user182944