Search code examples
hibernateormcollectionssecond-level-cachequery-cache

Hibernate - query caching/second level cache does not work by value object containing subitems


I have been struggling with the following problem:
I have a value object containing different panels. Each panel has a list of fields.

Mapping:

<class name="com.aviseurope.core.application.RACountryPanels" table="CTRY" schema="DBDEV1A" where="PEARL_CTRY='Y'" lazy="join">
<cache usage="read-only"/>
<id name="ctryCode">
<column name="CTRY_CD_ID" sql-type="VARCHAR2(2)" not-null="true"/>
</id>
<bag name="panelPE" table="RA_COUNTRY_MAPPING" fetch="join" where="MANDATORY_FLAG!='N'">
<key column="COUNTRY_LOCATION_ID"/>
<many-to-many class="com.aviseurope.core.application.RAFieldVO" column="RA_FIELD_MID" where="PANEL_ID='PE'"/>
</bag>
</class>

I use the following criteria to get the value object:

Session m_Session = HibernateUtil.currentSession();
            m_Criteria = m_Session.createCriteria(RACountryPanels.class);
            m_Criteria.add(Expression.eq("ctryCode", p_Country));
            m_Criteria.setCacheable(true);

As I see the query cache contains only the main select like

select * from CTRY where ctry_cd_id=?

Both RACountryPanels and RAFieldVO are second level cached. If I check the 2nd level cache content I can see that it cointains the RAFields and the RACountryPanels as well and I can see the select .. from CTRY where ctry_cd_id=... in query cache region as well.

When I call the servlet it seems that it is using the cache, but second time not. If I check the content of the cache using JMX, everything seems to be ok, but when I measure the object access time, it seems that it does not always use the cache.

Cheers Zoltan


Solution

  • I think that you need to also cache the association:

    <bag name="panelPE" table="RA_COUNTRY_MAPPING" fetch="join" where="MANDATORY_FLAG!='N'">
    
      <cache usage="read-write"/>
    
      <key column="COUNTRY_LOCATION_ID"/>
      <many-to-many class="com.aviseurope.core.application.RAFieldVO" column="RA_FIELD_MID" where="PANEL_ID='PE'"/>
    </bag>