Java 一对多关联的二级缓存
我正在使用Hibernate 3.2.5 我在Java 一对多关联的二级缓存,java,database,hibernate,orm,ehcache,Java,Database,Hibernate,Orm,Ehcache,我正在使用Hibernate 3.2.5 我在部门和培训表之间有一对多关系。启用二级缓存(使用EHCache),并在dept.cfg.xml和`training.hbm.xml文件中创建以下条目以缓存数据 <cache usage="read-only" /> 我在dept.hbm.xml文件中提到了映射,如下所示: //Mappings between POJO and DB Table <map name="trainingDetails" inverse="false"
部门
和培训
表之间有一对多关系。启用二级缓存(使用EHCache),并在dept.cfg.xml
和`training.hbm.xml文件中创建以下条目以缓存数据
<cache usage="read-only" />
我在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>
请告诉我我遗漏了什么以及如何解决此问题。如果您告诉Hibernate将
部门
实体缓存在二级缓存中,对于每个缓存的部门
,它将存储deptId
和deptName
字段的值。但是,默认情况下,它不存储trainingDetails
字段的内容。如果从二级缓存中读取部门,并且应用程序需要访问成员字段,Hibernate将转到数据库以确定集合的当前成员
如果希望Hibernate缓存members字段的内容,则需要通过向members
声明中添加cache
元素来告诉它这样做:
//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>
//POJO和DB表之间的映射
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();
//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>