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

    Setting the ID of the entity manually before persist

    trouby

      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.

        • 1. Re: Setting the ID of the entity manually before persist
          whafrog

           

          Why is that? The entity is NOT detached, it never got persisted...


          Well, you created it with "new", so it's not "attached" to the persistence engine, so it has to be detached... It's probably not an accurate message. persist() is for new rows, so it's probably not expecting ID to have a value, assuming that if it does have a value, it must have been previously retrieved.

          You've annotated your ID field with @GeneratedValue, so it's all or nothing. Either remove it and always provide the ID, or keep it and never do. Mixing the scenarios is a recipe for trouble anyway.


          • 2. Re: Setting the ID of the entity manually before persist
            trouby

            Ye, I figured it out,

            I just need it for initial data, and I wanted to keep the IDs synchronized,

            Well, thanks :)


            Asaf