title: JPA Add or update object
body: <p>I'm trying to save an object called Stat using EclipseLink. If the id exists in the db, update that object. If not, create a new object. Here is my object:</p>
  
  <pre><code>@Entity
  public class Stat {
  
      @Column
      @Id
      @GeneratedValue(strategy = GenerationType.AUTO)
      public long id;
  
      @JoinColumn
      @ManyToOne
      public User user;
  
  
      @Column
      public boolean accepted;
  
      @Column
      public boolean finished;
  
      public Stat() {
      }
  }
  </code></pre>
  
  <p>And here is my method for adding/updating the object.</p>
  
  <pre><code>public long addReplaceStat(Stat stat) {
              em.getTransaction().begin();
              Stat oldStat = em.find(Stat.class, stat.id);
              if (oldStat == null)
                  em.persist(stat);
              else
                  em.merge(stat);
              em.getTransaction().commit();
  
              em.getTransaction().begin();
              Stat newStat = em.find(Stat.class, stat.id);
              if (newStat != null)
                  em.refresh(newStat);
              em.getTransaction().commit();
  
              return stat.id;
          }
  </code></pre>
  
  <p>My problem is that I get exception at em.refresh() saying "The attribute [id] of class [User] is mapped to a primary key column in the database. Updates are not allowed." And I don't understand why. Shouldn't refresh just update the values of my managed object without problem?</p>
  
  <p>What is the best idiom to do what I want (add or update)?</p>