title: Hibernate many-to-many mapping with existing values
body: <p>Using JPA2 and Hibernate</p>
  
  <p>I have two classes that are interrelated in the source data,</p>
  
  <p>Person class:</p>
  
  <pre><code>@Entity
  public class Person {
      @Id @Column("PERSON_ID")
      @GeneratedValue(strategy = GenerationType.AUTO)
      private long id;
      private String name;
      private String job;
      // getters &amp; setters
  }
  </code></pre>
  
  <p>And a Movie class:</p>
  
  <pre><code>@Entity
  public class Movie {
      @Id @Column("MOVIE_ID")
      private long id;
      private String movieName;
      private String rating;
      @ManyToMany
      @JoinTable(name = "Movie_Actor",
        joinColumns = @JoinColumn(name="Movie_ID"),
        inverseJoinColumns = @JoinColumn(name="Person_ID")
      )
      private Set&lt;Person&gt; actors = new HashSet&lt;Person&gt;();
      // getters &amp; setters
  }
  </code></pre>
  
  <p>An actor is an instantiated <code>Person</code> with a job="Actor". 
  I plan on adding writers, directors, etc. to the mix later once this is working. Initially the Actor object may or may not have an ID (assuming later that we will read from the database and the <code>PERSON_ID</code> will have been populated).</p>
  
  <p>The actors are added to the <code>Movie</code> class:</p>
  
  <pre><code>Person actor = new Person();
  actor.setId=0;
  actor.setName="Actor Name";
  actor.setJob="Actor";
  movie.addActor(actor);
  
  From Movie.java
  public void addActor(Person actor) {
      actors.add(actor);
  }
  </code></pre>
  
  <p>I currently have code working that will insert the Person (actors) and Movie objects into the database (so long as they don't currently exist).</p>
  
  <p>What I would like to do is to update the <code>Person</code> object after enriching it with data from elsewhere (e.g. Quotes/pictures), persist it to the database <code>session.save(actor)</code> (which creates the <code>PERSON_ID</code> and then save the <code>Movie</code> object.</p>
  
  <p>The problem is when I update the <code>Movie</code> object with the updated <code>Person</code> (including the ID) then I get a unique constraint error on the database (because the <code>Person</code> already exists).</p>
  
  <p>How do I save the <code>Movie</code> object, with these pre-created <code>Person</code> objects that may or may not already have a relationship?</p>
  
  <p><hr/>
  EDIT: As per Thomas' suggestion, I have changed the session.save to session.saveOrUpdate, which solves the unique constant issue.</p>