Monday, 30 June 2014

Hibernate and Caching

One of the major problems of debugging, is that sometimes there are bugs, but they only happen some of the time1.

This makes it hard to fix, unless you can spot the pattern required for the bug to appear.

The Problem

My colleague at work had such a one.

Sometimes the software threw an exception and complained that the table in the database did not actually exist. Sometimes the program provided the data required, and went merrily on its way.

It's crazy for a database table to exist only some of the time.

It made sense in this case that the table didn't exist. Because that table wasn't in the database. The Entity was purely used as a 'View' and several methods gathered the information to load an instance of the Entity.

The Explanation

Hibernate provides caching, meaning that a lookup by Identifier for an Entity returns the Entity from the Cache without hitting the database, if the Entity has been loaded already once.

Turns out our method, which loaded an Entity, totally didn't work at all! It just happened to return a Cached instance in some cases without problems.

A cached instance that was loaded by using another method that did not rely on findByIdentifier (for example via "select new Constructor()").


[1] The Kingdom of Transformation
[2] Hibernate - Object Identity

No comments:

Post a Comment