title: Collection Caching with Hibernate
body: <p>I have a Java/Spring application with database entities.
  One of the entities is a <code>DataSet</code>. 
  Each DataSet can have a parent <code>DataSet</code>.
  And a parent-<code>DataSet</code> has multiple (OneToMany) children.</p>
  
  <pre><code>    @OneToMany(fetch=FetchType.LAZY)
      @IndexColumn(name = "order_id")
      @JoinColumn(name = "parent_dst_id")
      @Fetch(FetchMode.SELECT)
      @Cache(usage = org.hibernate.annotations.CacheConcurrencyStrategy.READ_WRITE)
      public List&lt;DataSet&gt; getChildren()
      {
          return children;
      }
  </code></pre>
  
  <p>After several years a lot of DataSets grouped under some parent DataSets.</p>
  
  <pre><code>parentDataset.getChildren().size() // &gt; 200.000
  </code></pre>
  
  <p>In the code (and I'm not sure if this is the correct way) the following lines are executed when adding a new dataset (survey) to a parent:</p>
  
  <pre><code>surveyDataset.setParent(parentDataset);
  parentDataset.getChildren().add(surveyDataset);
  </code></pre>
  
  <p>Until recently the <code>children</code> weren't cached at all. The 2nd statement then resulted in long running queries on the database.</p>
  
  <p>Now recently we added <code>datasets.children</code> to the cache. That way, everything goes really fast.</p>
  
  <p>Until...</p>
  
  <p>.. another child-dataset is added (under the same parent!) it becomes really slow again (ie: it starts querying the db again). </p>
  
  <p>I think that the cache is getting evicted or cleared or whatever and that that is the reason for querying again.</p>
  
  <p>See also: <a href="http://planet.jboss.org/post/collection_caching_in_the_hibernate_second_level_cache" rel="nofollow noreferrer">http://planet.jboss.org/post/collection_caching_in_the_hibernate_second_level_cache</a> (<strong>TLDR</strong>: "Hibernate doesn’t update the collection in the cache, it just removes it.")</p>
  
  <p>I tried to understand logging (net.sf.ehcache=DEBUG and org.hibernate.SQL=DEBUG) but thats difficult.</p>
  
  <p>So I'm stuck with a few questions</p>
  
  <p>1) What do I have to do to prevent loading all child-datasets again (all siblings from the new dataset)?
  2) How can I debug what is happening to my cache? Does it evict the parent? or also all children? As explained in the article it probably will reload the entire collection. </p>