Say we have the following two entities.
Library
public class Library
{
private Collection<Book> books = new ArrayList<Book>();
public boolean add(Book book)
{
return books.add(book);
}
public boolean remove(Book book)
{
return books.remove(book);
}
}
Book
public class Book
{
private Library library;
public setLibrary(Library library)
{
this.library = library;
}
}
This is a bi-directional relationship which will most likely break pretty quick. Even though you add a book to a library, the library of the book is not updated. And even though you update the library of a book, the library isn’t updated.
So, how would you maintain this bi-directional relationship in a good way? I could of course just do an add+remove in the setLibrary and vice versa, but this would as far as I can see cause a loop which would probably end in a StackOverflowError.
Define a “owner” for the relation. Does the library “own” the book or does the book own the library?
The answer to that question tells you who updates the “slave” entity.
I feel that the library owns the book, so the “add book to library” code should go into the library which will then update the back references.