Hibernate Ehcache brainfart moment

Had a brainfart moment the other day when working with cloudgrove.com and determining cache hit rates of objects. When you’re using Hibernate, the secondary cache is only employed when fetching objects by primary key. Otherwise it has to go back to the database to make sure that the selection criteria is still accurate. You can only guarantee an object and return from cache when you fetch it by unique identifier.

Keeping this in mind changes a few things about how I’m laying out the object structure. I had a score object that relates to both a content object and user object. Because Hibernate seriously discourages compound keys, I initially went with a primary key that wasn’t related to the other two items. However, the primary use case for the score object is to select the score by (contentId, userId) so I’m going to change the object to still have those two fields but to have a primary key that is a concatenation of the two fields. This way I can select the object through Hibernate using the secondary cache without having to do a select by criteria which always hits the database.