tags:

views:

66

answers:

1

I have a bidirectional many-to-many class:

public class A{
 @ManyToMany(mappedBy="listA")
 private List<B> listB;
}
public class B{
 @ManyToMany
 private List<A> listA;
}

Now I save a listA into B:

b.setListA(listA);

This all works fine until I turn on second-level caching on the collection a.ListB. Now, when I update the list in B, a.listB does not get updated and remains stale.

How do you get around this?

Thanks, Dwayne

A: 

Are you setting both sides of your bidirectional link between A and B correctly? A typically approach is to use defensive methods like this:

public class B {
    @ManyToMany
    private List<A> listA;

    public void addToListA(A a) {
        this.listA.add(a);
        a.getListB().add(this);
    }

    public void removeFromListA(A a) {
        this.listA.remove(a);
        a.getListB().remove(this);
    }
}
Pascal Thivent
This is going to be hard as I get updates from a client where they send List<A> to put into B. i.e. I need to call b.setListA(listA).
DD
@DD And how do you set the reference to `b` for all element of `listA`? I'm not staying the above solution is the only way to do it but if you don't, your bidirectional association is broken, which may explain the strange behavior you're seeing.
Pascal Thivent
I'm not updating the association at both ends...it seems to all work fine except for the caching. How would I do it otherwise if I don't want to use add and subtract methods (which would be hard as I am dealing with updating lists not adding/subtracting objects)? I guess I could use a uni-directional association and use queries at the other end.Also I dont really understand why you need to update both ends, if only one end is persisted? Does hibernate recognise that you have change the inverse side when you flush even though I'm not calling save on that particular object?
DD
@DD For background on this, check [1.2.6. Working bi-directional links](http://docs.jboss.org/hibernate/core/3.3/reference/en/html/tutorial.html#tutorial-associations-usingbidir). Your current implementation is broken.
Pascal Thivent
Yes...I dont really see the point in updating the other side...its not being persisted and I reload the object when I need it. If I just put in some junk like always setting the other side to null then that tells hibernate to expire the cache.
DD
@DD I give up, do whatever you want :)
Pascal Thivent