title: saving entity with referenced dependent entities using hibernate
body: <p>We are using Hibernate as persistency layer and have complex object model. Without exposing the real data model I want to explain the problem using the following simple example.</p>
  
  <pre><code>class Person {
      private Integer id; //PK
      private String name;
      private Account account;
      // other data, setters, getters
  }
  
  
  class Account {
      private Integer id; //PK
      // other data, setters, getters
  }
  </code></pre>
  
  <p>The DB mapping is defined using HBM as following:</p>
  
  <pre><code> &lt;class name="Person" table="PERSON"&gt;
      &lt;id name="id" column="ID"&gt;
          &lt;generator class="native"/&gt;
      &lt;/id&gt;
      &lt;version name="version" type="java.lang.Long"/&gt;
      &lt;property name="name" type="java.lang.String" length="50" column="NAME"/&gt;
      &lt;many-to-one name="account" column="ACCOUNT_ID"
                  class="com.mycompany.model.Account"/&gt;
  
  &lt;/class&gt;
  </code></pre>
  
  <p>I have to save new populated instance of <code>Person</code> linked to existing <code>Account</code>. The call is originated by web client, so at my layer I get instance of Person referenced to instance of <code>Account</code> that holds its ID only. </p>
  
  <p>If I try to call <code>saveOrUpdate(person)</code> the following exception is thrown:</p>
  
  <pre><code>org.hibernate.TransientObjectException: 
  object references an unsaved transient instance - save the transient instance before flushing: 
  com.mycompany.model.Account
  </code></pre>
  
  <p>To avoid this I have to find the persisted object of <code>Account</code> by ID and then call <code>person.setAccount(persistedAccount)</code>. In this case everything works fine. </p>
  
  <p>But in real life I deal with dozens of entities referenced to each other. I do not want to write special code for each reference.</p>
  
  <p>I wonder whether there is some kind of generic solution for this problem.  </p>