title: hibernate 4 handle unique index exception
body: <p>I have a system based on hibernate 4. I have an unique constraint in a table and need to handle it the following way:</p>
  
  <pre><code>try{
      getMyService().create(myobj);
  }catch(PersistenceException p){
    //constraint fails
      myobj.setConstraintColumn("new non unique value");
     getMyService().create(myobj);//should save it
  }
  </code></pre>
  
  <p>unfortunately I can't change the design of the system so I need just to figure it out this way.</p>
  
  <p><strong>EDIT</strong></p>
  
  <p>I get the following exception: </p>
  
  <pre><code>org.hibernate.AssertionFailure: null id in entry (don't flush the Session after an exception occurs)
  </code></pre>
  
  <p>The code of create method:</p>
  
  <pre><code> public E create(E entity) {
          entityManager.persist(entity);
          entityManager.flush();
          entityManager.refresh(entity);
          return entity;
   }
  </code></pre>