title: Inserting the same object as property in Hibernate+Spring
body: <blockquote>
    <p><strong>Possible Duplicate:</strong><br>
    <a href="https://stackoverflow.com/questions/2144697/spring-hibernate-a-different-object-with-the-same-identifier-value-was-alrea">Spring + Hibernate : a different object with the same identifier value was already associated with the session</a>  </p>
  </blockquote>
  
  
  
  <p>I have the following object (simplified) as a JavaBean:</p>
  
  <pre><code>public class Person {
    private Integer id;
    private City cityOfBirth;
    private City city;
    // ...
  }
  </code></pre>
  
  <p>And in my spring form I have 2 select combos in order to choose both cities, as follows:</p>
  
  <pre><code>&lt;form:form method="post" action="" commandName="person"&gt;
  City of birth: &lt;form:select path="cityOfBirth" items="${ cities }" itemValue="id" /&gt;
  City: &lt;form:select path="city" items="${ cities }" itemValue="id" /&gt;
  ...
  &lt;/form:form&gt;
  </code></pre>
  
  <p>My PropertyEditor for the City class would simply call to my CityDao's get, wich is the following:</p>
  
  <pre><code>@Component
  public class CityDaoImpl implements CityDao {
    private @Autowired HibernateTemplate hibernateTemplate;
  
    public City get (Integer id) {
      return (City) hibernateTemplate.get(City.class, id);
    }
  }
  </code></pre>
  
  <p>And my PersonDao would do this in order to save the instance:</p>
  
  <pre><code>public void save (Person person) {
    hibernateTemplate.saveOrUpdate (person);
  }
  </code></pre>
  
  <p>Everything works OK when I try to save a Person with 2 different cities, but when I choose the same City I obtain the following error:</p>
  
  <pre><code>org.hibernate.NonUniqueObjectException: a different object with the same identifier value was already associated with the session: [com.project.si.models.common.City#90]
  </code></pre>
  
  <p>I've read in other posts that this happens because Hibernate Session is currently aware of the previous City obtained when the propertyEditor called <code>cityDao.get(id)</code>, so I'm supposed to use merge() somewhere, but I don't get where should I apply this..</p>