title: JPA EntityManager persist() causing object to appear detached even though an error was thrown
body: <p>Hi I have a simple DAO with the below function.</p>
  
  <pre><code>    public element createElement(Element e){
  
      em.persist(e);
      em.flush();
  
      return e;
  }
  </code></pre>
  
  <p>The Entity table has a unique constraint on the pair (type,value) and I have a test below:</p>
  
  <pre><code>    public void testCreateElement() throws DataAccessException {
          // Start with empty Element table
  
          Element e = new Element();
          e.setType(myType.OTHER);
          e.setValue("1");
          dao.createElement(e);
  
          e = new Element();
          e.setType(MyType.OTHER);
          e.setValue("1");
          try{
                  // this should violate unique constraint of database.
                  dao.createElement(e);
          } catch (Exception ex) {
              System.out.println(ex);
          }
  
          e.setValue("2");
          try{
              // I expect this to work as there is no element with these values.
              dao.createElement(e);
          } catch (Exception ex) {
              System.out.println(ex);
          }
      }
  </code></pre>
  
  <p>My first caught error happens as I expect since I know that I'm violating the constraint, the second try/catch shouldn't throw an error as far as i'm concerned, but it does, what I get its this:</p>
  
  <pre><code>javax.persistence.PersistenceException: org.hibernate.PersistentObjectException: detached entity passed to persist: com.mypackage.Element
  </code></pre>
  
  <p>So it seems calling persist() on "e" even though it wasn't persisted has caused hibernate to think it's a detached entity.</p>
  
  <p>This is annoying because these functions are getting used by a JSF front end that is dealing with the ConstraintViolation exception, but deliberately holding on to the object so that the user can change one of the fields and try again, and they get the detached entity error.</p>
  
  <p>Is this behaviour a hibernate bug because I don't think it should be doing this really? Is there a way around this at the DAO level so that persist won;t treat my object as detached if it's not actually persisted?</p>
  
  <p>Regards,</p>
  
  <p>Glen x</p>