title: how to use em.merge() to insert OR update for jpa entities if primary key is generated by database?
body: <p>I have an JPA entity like this:</p>
  
  <pre><code>@Entity
  @Table(name = "category")
  public class Category implements Serializable {
      private static final long serialVersionUID = 1L;
  
      @Id
      @GeneratedValue(strategy = GenerationType.IDENTITY)
      @Basic(optional = false)
      @Column(name = "id")
      private Integer id;
  
      @Basic(optional = false)
      @Column(name = "name")
      private String name;
  
      @OneToMany(cascade = CascadeType.ALL, mappedBy = "category")
      private Collection&lt;ItemCategory&gt; itemCategoryCollection;
  
      //...
  }
  </code></pre>
  
  <p>Use Mysql as the underlying database. "name" is designed as a unique key. Use Hibernate as JPA provider. </p>
  
  <p>The problem with using merge method is that because pk is generated by db, so if the record already exist (the name is already there) then Hibernate will trying inserting it to db and I will get an unique key constrain violation exception and not doing the update . Does any one have a good practice to handle that? Thank you!</p>
  
  <p>P.S: my workaround is like this:</p>
  
  <pre><code>public void save(Category entity) {
  
      Category existingEntity = this.find(entity.getName());
      if (existingEntity == null) {
         em.persist(entity);
         //code to commit ...
      } else {
          entity.setId(existingEntity.getId());
          em.merge(entity);
          //code to commit ...
      }
  }
  
  public Category find(String categoryName) {
      try {
          return (Category) getEm().createNamedQuery("Category.findByName").
                  setParameter("name", categoryName).getSingleResult();
      } catch (NoResultException e) {
          return null;
  
      }
  }
  </code></pre>