title: JPA - create-if-not-exists entity?
body: <p>I have several mapped objects in my JPA / Hibernate application. On the network I receive packets that represent updates to these objects, or may in fact represent new objects entirely. </p>
  
  <p>I'd like to write a method like </p>
  
  <pre><code>&lt;T&gt; T getOrCreate(Class&lt;T&gt; klass, Object primaryKey)
  </code></pre>
  
  <p>that returns an object of the provided class if one exists in the database with pk primaryKey, and otherwise creates a new object of that class, persists it and returns it.</p>
  
  <p>The very next thing I'll do with the object will be to update all its fields, within a transaction. </p>
  
  <p>Is there an idiomatic way to do this in JPA, or is there a better way to solve my problem? </p>