title: Automatically reusing existing entity in ManyToMany/ManyToOne relationship (JPA)
body: <p>JPA and Hibernate are used to retrieve and persist entities. There is a <code>User</code> table and it contains a <code>Country</code>, which is represented in another table.</p>
  
  <p>I would like to insert a new user into <code>User</code> table. This new user is from country that is already inserted in the <code>Country</code> table. To assign the new user the existing country I could retrieve the country object from the database and set it to the <code>User</code> object - it works as expected, a relationship is created between user and the existing country, no new rows are inserted to <code>Country</code> table. </p>
  
  <p>Is it possible to get the same behavior without retrieving <code>Country</code> objects from database, based just on the value that I set to the <code>Country</code> object in the JPA entity in Java?</p>
  
  <p>For example:</p>
  
  <pre><code>User user = new User("test user");
  user.setCountry(new Country("USA"));
  entityManager.persist(user);
  </code></pre>
  
  <p>I would like JPA/Hibernate to automatically check if the country, which code is USA (code is saved in a column in Country table and it is unique), already exists in the database. If it does - use the existing Country object so that a new entry in the database would not be created, if it does not exist - insert a new country in the Country table.</p>
  
  <p>Thank you!</p>