I've got a one-to-many relationship: Parent record with n Child records. These records are frequently used and read-only and are good candidates for caching.
Here is an approximation of my Hibernate mapping:
`<class name="Parent" table="Parent>
<cache usage="read-only"/>
<id name="primary_key"/>
<property name="natural_key"/>
<set name="children" lazy="false" fetch="join">
<cache usage="read-only"/>
<key-column name="parent_id"/>
<one-to-many class="Child"/>
</set>
</class>
<class name="Child" table="Child">
<cache usage="read-only"/>
<id name="primary_key"/>
<property name="parent_id"/>
</class>`
I frequently fetch the Parent by a natural key, rather than a primary key, so I need to enable Query Caching in order to take advantage of the 2nd Level Cache (I use ehcache).
Here's the problem: when I fetch a Parent and get a hit in the query cache, it becomes a "fetch by primary key" query. This is fine for the "one" end of my one-to-many. If the Parent is not found in the cache, it is fetched from the DB. If my n Child records are not found in the cache, Hibernate fetches them using n subsequent select queries. N+1 select problem.
What I want is a way to cache the collection of Child objects, keyed by the parent_id. I want Hibernate to look for my collection in the cache as a whole, rather than as a bunch of individual records. If the collection is not found, I want Hibernate to fetch the collection using 1 select statement - fetch all Child with parent_id=x.
Is this too much to ask from Hibernate + ehcache?