title: How to prevent a loop in a bi-directional relationship
body: <p>Say we have the following two entities.</p>
  
  <p><strong>Library</strong></p>
  
  <pre><code>public class Library
  {
      private Collection&lt;Book&gt; books = new ArrayList&lt;Book&gt;();
  
      public boolean add(Book book)
      {
          return books.add(book);
      }
      public boolean remove(Book book)
      {
          return books.remove(book);
      }
  }
  </code></pre>
  
  <p><strong>Book</strong></p>
  
  <pre><code>public class Book
  {
      private Library library;
      public setLibrary(Library library)
      {
          this.library = library;
      }
  }
  </code></pre>
  
  <p>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.</p>
  
  <p>So, how would you maintain this bi-directional relationship in a good way? I could of course just do an <code>add</code>+<code>remove</code> in the <code>setLibrary</code> and vice versa, but this would as far as I can see cause a loop which would probably end in a <code>StackOverflowError</code>.</p>