title: Duplicate key issue with Hibernate
body: <p>Using Hibernate 4.0 I have three hibernate entities:</p>
  
  <p>Song, CoverArt, CoverImage</p>
  
  <p>Songs represents music file, CoverImage represents an image and CoverArt is used to relate CoverImages to Songs, a song can contain multiple cover images.</p>
  
  <p>Song and CoverArt have a primary key generated automatically by Hibernate. But Cover Image primary key done manually, constructed as a MessageDigest of the image data. I do this because the same image can be used by many songs and I dont want seperate instances of the same image stored multiple times in the database, also because the key can be constructed from the data I can check in the database whether the file already exist and if so retrieve it rather than constructing a new CoverImage.</p>
  
  <p>The trouble is my application is multithreaded and Hibernate doesnt actually commit things to the database immediaely, so thread 1 may check if the coverimage is already in the database, find that it isnt and construct a new  Song, CoverArt and CoverImage objects. But by the time the data gets committed to the database a CoverImage may have been added by a seperate thread so I get an exception because my new CoverImage has the same key
  as an existing one</p>
  
  <p>Im using </p>
  
  <pre><code>session.merge(coverImage);
  </code></pre>
  
  <p>so I thought that would handle this, but it doesn't seem to help</p>