我正在使用Hibernate 3.2.5。一對多協會的二級緩存
我有Department
和Training
表之間的一對多關係。啓用了二級緩存(使用EHCache),並且在dept.cfg.xml
和用於緩存數據的`training.hbm.xml文件中都創建了以下條目。
<cache usage="read-only" />
問題描述
這是第一次,DB命中是獲得兩個Dept
和Training
記錄完成的。第二次,從緩存中獲取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();
請讓我知道我缺少什麼以及如何解決這個問題。
謝謝,這解決了我的問題,很好的解釋:) – user182944