我正在使用休眠 3.2.5。
Department
我在和Training
表之间有一对多的关系。启用了二级缓存(使用 EHCache),并且在dept.cfg.xml
`training.hbm.xml 文件和 `training.hbm.xml 文件中都创建了以下条目以缓存数据。
<cache usage="read-only" />
问题描述
第一次,数据库命中是为了获取Dept
和Training
记录。第二次,Department
从缓存中获取数据,但是为了获取Training
数据,再次完成了 DB 命中 - 为什么?我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();
请让我知道我错过了什么以及如何解决这个问题。