Hello!
There is a weird behaviour in manipulating bidirectional association having inverse accociation end marked as cached (one-to-many, many-to-many, does not matter).
For example, two classes
Code:
class A {
List<B> bs;
}
class B {
List<A> as;
}
one end of this association have to be mapped inverse, since both can update link table, let A.bs be the inverse one.
We update B.as, remove some elements, add some elements. Persist change. If B.as accociation end is marked as cached <cache usage="rw"/>, hibernate invalidate cache region, next time B.as accessed fresh collection copy is retrived from db.
But if A.bs is marked as cached no cache region changes happend upon B.as persistence. This leads to stale collection A.bs, containing old set of B elements (removed elements present, new elements - not).
If any element B from old collection is removed (actually A element removed from B.as collection), upon initialization of A.bs exception thrown.
Temporary solution is to invalidate cache regions for A.bs collection manually, e.g. sessionFactory.evictCollection("A.bs", id), there id - is modified A element id from B.as collection.
Two questions:
Is this an optimal solution?
Why hibernate does not do this automatically, after all it knows - someone (namely not inverse association end) is responsible for collection modifications?
Thank you!