title: Understanding Hibernate saveOrUpdate and the Persistence Life Cycle
body: <p>Let's look at a simple example of a dog and a cat that are friends.  This isn't a rare occurrence.  It also has the benefit of being much more interesting than my business case.</p>
  
  <p>We want a function called "saveFriends" that takes a dog name and a cat name.  We'll save the Dog and then the Cat.  For this example to work, the cat is going to have a reference back to the dog.  I understand this isn't an ideal example, but it's cute and works for our purposes.</p>
  
  <p><strong>FriendService.java</strong></p>
  
  <pre><code>public int saveFriends(String dogName, String catName) {
      Dog fido = new Dog();
      Cat felix = new Cat();
  
      fido.name = dogName;
      fido = animalDao.saveDog(fido);
  
      felix.name = catName;
      [ex.A]felix.friend = fido;
      [ex.B]felix.friend = animalDao.getDogByName(dogName);
      animalDao.saveCat(felix);
  }
  </code></pre>
  
  <p><strong>AnimalDao.java</strong> <em>(extends HibernateDaoSupport)</em></p>
  
  <pre><code>public Dog saveDog(Dog dog) {
      getHibernateTemplate().saveOrUpdate(dog);
      return dog
  }
  
  public Cat saveCat(Cat cat) {
      getHibernateTemplate().saveOrUpdate(cat);
      return cat;
  }
  
  public Dog getDogByName(String name) {
      return (Dog) getHibernateTemplate().find("from Dog where name=?", name).get(0);
  }
  </code></pre>
  
  <p>Now, assume for a minute that I would like to use either example A or example B to save my friend.  Is one better than the other to use?  </p>
  
  <p>Furthermore, won't example B get you the infamous "not-null property references a null or transient value" error?  I'm only guessing here but I would think this is because the Dog is still in the session.</p>
  
  <p>I'll understand if neither of those examples work, but please explain why.</p>