Hibernate, second level cache and Clustering

So, I ran into a nasty little problem at work when trying to cluster the hibernate second level cache. We were using hibernate 3.2.1 GA and ehcache 1.2 and when replicating the caches between multicast nodes, random classcast exception occured when retrieving an object from secondlevel cache(slc). Turns out that the problem was with the way hibernate stores it’s objects in de slc, by default it stores the attribute values of the properties in an array, this array gets replicated to the various nodes. Normally this would not be a problem, but it seems that the order of the properties as determined by hibernate for persistentclasses (using annotations) is not fixed between SessionFactories. This caused the classcast exceptions, because where one instance inserted a String, the next instance expected a Date or Long or whatever.

We’ve even tested this by deploying the same WAR file on the same machine (same tomcat etc.) the problem will still occur. There is a way around this problem, luckily, it took us a while to find it:

If you set the hibernate property hibernate.cache.use_structured_entries to true, hibernate will use a HashMap to store attribute values by their property name. This way, the retrieval of the properties is guaranteed, even when the order of the properties isn’t. I’m guessing that this problem only affects hibernate when using annotations, since otherwise the order of the properties is already set in the XML, but I’ve not tested it.