2 Replies Latest reply on Aug 9, 2007 12:40 PM by asaf sh

    Setting the ID of the entity manually before persist

    asaf sh Expert

      Hello,

      I have some simple entities with ID annotated as:

      @Entity
      @Table(name="MY_TABLE")
      public class MyEntity {
      private Long id;
      
      @Id @GeneratedValue
      @Column(name="ID")
      public Long getId() {
       return id;
      }
      
      public void setId(Long id) {
       this.id= id;
      }
      }
      


      When I try to create a new entity and set its ID manually I get an exception,

      here's a sample code:

      MyEntity my = new MyEntity();
      my.setId(new Long(4));
      my.setSomeMoreMethods(...)
      ..
      em.persist(my);
      


      I get the following exception


      23:02:31,281 FATAL [application] Failed to perform the operation, failure message: javax.persistence.PersistenceExceptio
      n: org.hibernate.PersistentObjectException: detached entity passed to persist: velo.entity.ActionLanguage
      javax.faces.el.EvaluationException: Failed to perform the operation, failure message: javax.persistence.PersistenceExcep
      tion: org.hibernate.PersistentObjectException: detached entity passed to
      ...


      Why is that? The entity is NOT detached, it never got persisted, and I would like to set the ID manually sometime before persisting...

      btw: If I invoke em.merge(my); it works, but it persist the object with new IDs


      So, is that possible? with TopLink it wasn't a trouble,


      Thanks,


      Asaf.