use*_*944 2 java database orm hibernate ehcache
我正在使用Hibernate 3.2.5。
我Department和Training表之间有一对多的关系。启用了第二级缓存(使用EHCache),并且在andtraining.hbm.xml dept.cfg.xml文件中都进行了以下输入以缓存数据。
<cache usage="read-only" />
Run Code Online (Sandbox Code Playgroud)
问题描述
第一次,数据库命中用于获取Dept和Training记录。第二次,Department从高速缓存中获取Training数据,但是为了获取数据,再次执行数据库命中-为什么?我希望Training也可以从缓存中获取此数据,而不是每次都访问数据库。
这是Dept.java文件:
private int deptId;
private String deptName;
private Map trainingDetails;
Run Code Online (Sandbox Code Playgroud)
我已经在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>
Run Code Online (Sandbox Code Playgroud)
这是我尝试的代码:
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();
Run Code Online (Sandbox Code Playgroud)
请让我知道我在想什么以及如何解决这个问题。
如果您告诉Hibernate Department在第二级缓存中缓存实体,则对于每个缓存Department,它将存储deptId和deptName字段的值。但是,默认情况下它不存储该trainingDetails字段的内容。如果Department从二级缓存中读取了a ,并且应用程序需要访问member字段,则Hibernate将转到数据库以确定集合的当前成员。
如果您想让Hibernate缓存member字段的内容,则需要通过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>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1808 次 |
| 最近记录: |