Search code examples
javaassociationsbidirectionalinverse

Generic Java Framework to Manage Bidirectional Associations and Inverse Updates


I've been looking for a generic way to deal with bidirectional associations and a way to handle the inverse updates in manual written Java code.

For those who don't know what I'm talking about, here is an example. Below it are my current results of (unsatisfying) solutions.

public class A {
    public B getB();
    public void setB(B b);
}

public class B {
    public List<A> getAs();
}

Now, when updating any end of the association, in order to maintain consistency, the other end must be updated as well. Either manually each time

a.setB(b);
b.getA().add(a);

or by putting matching code in the setter / getter and use a custom List implementation.

I've found an outdated, unmaintained project whose dependencies are no longer available (https://e-nspire-gemini.dev.java.net/). It deals with the problem by using annotations that are used to inject the necessary code automatically.

Does anyone know of another framework that deals with this in a generic, unobtrusive way ala gemini?

ciao, Elmar


Solution

  • google collections (from google's internal code) -- http://code.google.com/p/google-collections/ is Java Generics compatible(not only compatible, uses generics very well)

    Class BiMap -- http://google-collections.googlecode.com/svn/trunk/javadoc/index.html?http://google-collections.googlecode.com/svn/trunk/javadoc/com/google/common/collect/package-summary.html allows for Bidirectional associations.

    Some of these classes are expected to make their way into JDK 7.