views:

508

answers:

1

I've got a pair of Hibernate entities, A and B, that are related via a bidirectional many-to-many relationship, as described here - ie, each entity has a bag referencing a collection of the other type of entity, with a link table comprising the primary key of each entity.

I am also using Hibernate L2 caching to cache the collection values, like this:

<bag name="xyz" table="XYZ" ...>
    <cache usage="nonstrict-read-write"/>
</bag>

The problem I am finding is that when I update the relationship from one side, the cached collection of items on the other side is not updated.

For example:

A a = session.get(1L, A.class);

B b = a.getBs().get(0);
Long bId = b.getId();

a.getBs().remove(0) // delete the B from A
// ... flush and commit the transaction...

B b2 = session.get(bId, B.class);
Collection<A> as = b2.getAs();

Collection as still contains a reference to a, even though the database state reflects the fact that the relationship was deleted. After invalidating the cache, Hibernate will return the correct results.

Does hibernate has any mechanisms for handling cache invalidation of related entities, or would I need to remove the relationship from both ends?

I am using Hibernate 3.2.6.

+1  A: 

By definition you need to remove from both sides. It makes sense from a technical perspective as basically both collections are cached independently.

Of course it's nonsense from a practical perspective and many people will trip over it.

Mainguy