一对多关联的二级缓存

时间:2013-06-30 08:58:17

标签: java database hibernate orm ehcache

我正在使用Hibernate 3.2.5。

我在DepartmentTraining表之间存在一对多的关系。启用了第二级缓存(使用EHCache),并在dept.cfg.xml和`training.hbm.xml文件中进行以下输入以缓存数据。

<cache usage="read-only" />

问题说明

首次获得数据库命中以获取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();

请让我知道我错过了什么,以及如何解决这个问题。

1 个答案:

答案 0 :(得分:5)

如果您告诉Hibernate在第二级缓存中缓存Department个实体,则对于每个缓存的Department,它将存储deptIddeptName字段的值。但是,它默认不存储trainingDetails字段的内容。如果从二级缓存中读取Department并且应用程序需要访问成员字段,则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>