views:

669

answers:

2

hi
I'm trying to understand how hibernate query cache really works. What I see now is that Hibernate does not update its second-level cache automatically when I insert new entities into the database (although I'm using only Hibernate calls). The only way I have found to make it work was to manually clean the cache after inserting new entities.

Here is the more concrete example. I have a persistent entity called Container which can have many Items. I wanted to have all the items cached:

@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
class Item 
{
  // rest of the code ...
}

class Container {
  @Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public List getItems() { ... } // rest of the code ... }

The problem which I have noticed is that when I:

1) read some Containers from the db into memory (together with the corresponding items)

   String hql =
      "from Container c left join fetch c.items where c.type = 1";
   List<Item> list = hibernateTemplate.find(hql);

2) insert new Item for a chosen Container

   hibernateTemplate.save(item)

3) repeat the first step
then in the 3rd step I cannot see the item I have inserted in the second step. I see them only if I clean the cache manually after inserting new items:

   sessionFactory.evictCollection("Container.items", updatedContainerId)

My gut feeling tells me that Hibernate should do such a cache invalidation automatically. Has anyone seen it working? Am I doing something wrong or is it just not supported?

Thanks in advance for the answer. Greetings Tom

+1  A: 

Hibernate stores data from queries by using a key composed of the query (or query name) and the value of the specified parameters. I guess it can not easily know what cache to invalidate when you modify data.

To solve this problem you should simply call SessionFactory.evictQueries.

bernardn
+1  A: 

You might find my blog on query cache workings to be helpful in understanding what the query cache does and why it might not work the way you think it works:

Alex Miller