2012-01-16

Hibernate - collection was not processed by flush

Recently I got the following exception from Hibernate:
collection was not processed by flush
What happened? I have the following class structure.
Artist -> Album -> Song (parent -> child)

Library -> Stat (parent -> child)

Song - Stat (association)
Artist and Library are aggregates in DDD sense. Artist is the parent of Album, Album is the parent of Song. Library is the parent of Stat. What's important, there's also a bidirectional relationship between Song and Stat (but no ownership). The exception occurred in the following situation:
  1. I had an Artist with one Album with one Song that had an association with one Stat being a child of its Library and that was created in Transaction 1.
  2. In Transaction 2, the whole thing was loaded again, a new Stat added, being a child of a new Library.
  3. Transaction 2 ended. Exception thrown.
So at the time when Transaction 2 ended I had a Song with 2 Stats, each referring to a different Library, but one of those Libraries was out of context, as it is lazy loaded from Stat.

The fix

The fix (or hack) was to eagerly load Library from Song. It's not ideal but it fixed the problem. There was no need to update this Library instance when transaction ended, so I'm wondering if it's a Hibernate defect...