0

I'm trying to get nHibernate to use second-level cache with a many-to-one relationship, however I can't find any clear explanation on how to set it up correctly. I found this How to get nhibernate to cache tables referenced via many-to-one - is my config correct?, but the example sJHonny provided is for one-to-many and it's not working for me when I adopt it. There are other posts going over this subject, but none of them are specific enough.

The XML config I provide works (I had to edit dramatically, so "hopefully" works), but lookup objects are being cached only when they are retrieved as DataObject is queried. I'd like to know 1) where/how to preload the LookupObject collection? 2) what if I assign this collection to a region and set expiration, then where/how do I reload the cache again? 3) how to change the DataObject's hbm.xml such that nHibernate doesn't generate a join with the LOOKUP table, i.e. such that lookup objects always come from the secondary cache, only getting the DATA.LOOKUP_ID from the db, not the LOOKUP.NAME?

LookupObject.hbm.xml

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" namespace="BusinessObjects" assembly="BusinessObjects">
  <class name="LookupObject" table="LOOKUP" mutable="false" batch-size="20">
    <cache usage="read-only" />   
    <id name="Id" column="ID" />
    <property name="Name" column="NAME" />
  </class>
</hibernate-mapping>

DataObject.hbm.xml

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" namespace="BusinessObjects" assembly="BusinessObjects">
  <class name="DataObject" 
         table="DATA" mutable="false">
    <composite-id>
      <key-property name="Id" column="ID"/>
      <key-property name="Date" column="DATE" type="Date"/>
    </composite-id>
    <many-to-one name="LookupObject" not-null="true" column="LOOKUP_ID" fetch="join">
  </class>
</hibernate-mapping>
Community
  • 1
  • 1
user1198049
  • 491
  • 5
  • 15

1 Answers1

0

I believe I answered my own questions. 1) For preloading the entire collection, I just needed to change my code such that the entire list of lookups is always pulled from the DB and cached, then I get the individual object by ID with LINQ. 2) Same as before. 3) I haven't tested this yet, but I need to remove fetch="join" from many-to-one element because otherwise the SQL join will still be generated and data will be still returned. Then set the lookup object without nHibernate by getting it from cache.

user1198049
  • 491
  • 5
  • 15