The bug in Hibernate that I reported yesterday turned out to be a bug in my Interceptor. To get to this conclusion, we did a bit more tracing through the code and managed to put together a minimal failing test (see the forum posting). I had read the Interceptor docs several months back when we implemented the first features we needed. Max from the Hibernate team reminded me of this requirement:
The Session may not be invoked from a callback (nor may a callback cause a collection or proxy to
be lazily initialized).
Oops. You’ll see in my test that my Interceptor is indeed causing a lazy collection to be initialized. The workaround I suggested, which involved deleting a couple lines of code, does actually solve this problem. It is, however, unclear what other problem might be caused by that change.
So, what’s the solution? For the case that I was dealing with today, it was simple to just not touch the Collections at all. There are other possible places that the Interceptor could cause a lazily loaded Collection to be initialized. My general strategy is this: use Hibernate.isInitialized to check it’s status. If it’s not initialized and I really need to use it, I’ll load the object up in a different Session.