title: Java JPA, Swing and Beans Binding: Changes to a OneToMany collection in entity not immediately reflected in GUI
body: <p>I am trying to learn JPA with Hibernate and binding it to a GUI built in Netbeans with Beans Binding. It is a application listing dogs. Each dog can have one to many puppies. You can add and delete dogs, and for each dog you can add and delete puppies.</p>
  
  <p>The dogs are displayed in a JList, when the user selects a dog its properties is shown in JTextFileds and its puppies are shown in a JTable. Adding/deleting dogs works fine because the list containing the Dog instances are Observable.</p>
  
  <p>The Dogs puppies are maintained in a Collection in the Dog class with getter and setter:</p>
  
  <pre><code>@OneToMany(targetEntity = Puppie.class, fetch = FetchType.EAGER, cascade = CascadeType.ALL)
  @JoinColumn(name = "dog_id")
  private Collection&lt;Puppie&gt; puppies;
  
  public Collection&lt;Puppie&gt; getPuppies() {
      if (puppies == null) {
          puppies = new ArrayList&lt;Puppie&gt;();
      }
      return puppies;
  }
  
  public void setPuppies(Collection&lt;Puppie&gt; puppies) {
      Collection&lt;Puppie&gt; oldPuppies = this.puppies;
      this.puppies = puppies;
      changeSupport.firePropertyChange("puppies", oldPuppies, puppies);
  }
  </code></pre>
  
  <p>When I add a puppie to the dog selected in the JList it is not reflected in the JTable immediately. I have to select another dog and then reselect the dog I added the puppy to to make it show up in the JTable. I am using the following add/delete puppie methods in the Dog class:</p>
  
  <pre><code>public void addPuppie(Puppie puppie) {
      getPuppies().add(puppie);
  }
  
  public void deletePuppie(Puppie puppie) {
      getPuppies().remove(puppie);
  }
  </code></pre>
  
  <p>The JTable is bound to the JList (and not the dogs list) with ${selectedElement.puppies} as binding expression.</p>
  
  <p>The setters in the Puppie class fire property changes when properties are set.</p>
  
  <p>This is the code for adding a puppie:</p>
  
  <pre><code>@Action
  public void addPuppy() {
      Puppie p = new Puppie();
      p.setName("new puppie");
      entityManager.persist(p);
  
      int selectedIndex = dogsJList.getSelectedIndex();
      Dog d = (Dog) dogList.get(selectedIndex);
      d.addPuppie(p);
      setSaveNeeded(true);
  }
  </code></pre>
  
  <p>Any help would be greatly appreciated! Let me know if you need more information.</p>
  
  <p>Regards,
  Henrik</p>