title: Best way to prevent unique constraint violations with JPA
body: <p>I have an <code>Keyword</code> and a <code>KeywordType</code> as entities. There are lots of keywords of few types. <br><br>When trying to persist the second keyword of a type, the unique constraint is violated and the transaction is rolled back. <br><br>Searching SO i found several possibilies (some of them from different contexts, so I'm not sure of their validity here) - <a href="https://stackoverflow.com/questions/3500096/lost-transaction-with-jpa-unique-constraint">this post</a> and <a href="https://stackoverflow.com/questions/2519902/elegantly-handling-constraint-violations-in-ejb-jpa-environment">this post</a> advise catching the Exception which would be of no use to me as I end up where I started and still need to somehow persist the keyword. 
  <br>Same applies to locking proposed for a different situaltion <a href="https://stackoverflow.com/questions/2641732/jpa-2-0-eclipselink-check-for-unique.">here</a> <br>Custom insert statements as proposed in <a href="https://stackoverflow.com/questions/3275100/jpa-and-unique-fields">this</a> and <a href="https://stackoverflow.com/questions/913341/can-hibernate-work-with-mysqls-on-duplicate-key-update-syntax">this</a> posts wouldn't work proper I guess, since I'm using Oracle and not MySQL and woulnd like to tie the implementation to Hibernate. <br><br>A different workaround would be trying to retrieve the type first in the code generating the keywords, and set it on the keyword if found or create a new one if not.<br><br>
  So, what would be the best - most robust, portable (for different databases and persistence providers) and sane approach here? </p>
  
  <p>Thank you.</p>
  
  <p>The involved entities:   </p>
  
  <pre><code>public class Keyword {
  
      @Id
      @GeneratedValue
      private long id;
  
      @Column(name = "VALUE")
      private String value;
  
      @ManyToOne
      @JoinColumn(name = "TYPE_ID")
      private KeywordType type;
      ...
  }
  </code></pre>
  
  <p>and</p>
  
  <pre><code>@Entity
  @Table(uniqueConstraints = {@UniqueConstraint(columnNames = { "TYPE" }) })
  public class KeywordType {
  
      @Id
      @GeneratedValue
      private long id;
  
      @Column(name = "TYPE")
      private String type;
      ...
  }
  </code></pre>