title: Save object in database if it does not already exist (Hibernate & Spring)
body: <p>I'm working on a Hibernate/Spring application to manage some movies.</p>
  
  <p>The class movie has a many to many relationship with the class genre.
  Both of these classes have generated id's using the GeneratedValue annotation.</p>
  
  <p>The genre is saved through the movie object by using @Cascade(CascadeType.SAVE_UPDATE)
  I have placed a unique constraint on the genre's type attribute (which is it's name; "Fantasy" for example).</p>
  
  <p>What I would like to do now is have Hibernate check if there is already a genre with type "Fantasy" and if there is, use that genre's id instead of trying to insert a new record.
  (The latter would obviously throw an error)</p>
  
  <p>Finally what I need is something like select-before-update but more like select-before-save.</p>
  
  <p>Is there such a function in Hibernate?</p>
  
  <p>Some code:</p>
  
  <p>Movie class</p>
  
  <pre><code>@Entity
  public class Movie {
  
  @Id
  @GeneratedValue(strategy=GenerationType.AUTO)
  private int id;
  
  private String name;
  
  @Lob
  private String description;
  
  @Temporal(TemporalType.TIME)
  private Date releaseDate;
  
  @ManyToMany
  @Cascade(CascadeType.SAVE_UPDATE)
  private Set&lt;Genre&gt; genres = new HashSet&lt;Genre&gt;();
  
  .... //other methods
  </code></pre>
  
  <p>Genre class</p>
  
  <pre><code>@Entity
  public class Genre {
  
  @Column(unique=true)
  private String type;
  
  @Id
  @GeneratedValue(strategy=GenerationType.AUTO)
  private int id
  
  ....//other methods
  </code></pre>