Thursday, November 22, 2012

Hibernate caching with multiple objects mapped to one table

I recently had to do some performance tuning on an old application which for some reason had a database table that was mapped to two different domain objects. The mapping is bizarre because the domain objects are actually the same thing but for some reason there are two representations in this application!

One thing I wanted to setup was the second level cache to see if this would improve performance however once I discovered the crazy mappings I wondered how hibernate was going to cache this.

I didn't have enough time to really dig into what Hibernate was doing but based on the cache logs it appears that it knows which tables the entities it is caching are from and invalidates the cache for both when one is updated. Interestingly it also maintains the query cache appropriately so that a fetch for one entity will prime the cache for the other!

I was pretty impressed by this as I was expecting these crazy mappings to confuse hibernate but it seemed to handle it fine. This was an older version though so hopefully it is still valid in the later releases.

If you are interested this was done using Hibernate 3.2 and eh cache 1.3 (ancient!).