1 Reply Latest reply on Feb 28, 2007 5:06 PM by Dustin Norlander

    EntityHome.persist - Getting the generated id?

    Dustin Norlander Apprentice

      Hi,

      I have an entity home class and I need to get the generated id (database generated) of the persisted object after calling persist (I would have thought this would be automatic?).. It always comes back as 0.

      Here is my entityHome class:

      @Name("userHome")
      public class UserHome extends EntityHome<User> {
       @In
       private EntityManager entityManager;
      
       public void setUserId(Integer id) {
       setId(id);
       }
      
       public Integer getUserId() {
       return (Integer) getId();
       }
      
       @Override
       protected User createInstance() {
       User u = new User();
       return u;
       }
      
       @Override
       public String persist() {
      
       String retval = super.persist();
       User u = this.getInstance();
       System.out.println("Persisted user: " + u.getName() + " id: " +
       u.getId() + " this.id: " + this.getId());
       return retval;
       }
      }


      And the entity:

      @Entity
      @Name("user")
      @Scope(SESSION)
      @Table(name = "User")
      public class User implements java.io.Serializable {
      
       // Fields
       private int id;
      
       private String name;
      
       private String password;
      
       // Constructors
      
       /** default constructor */
       public User() {
       }
      
       // Property accessors
       @Id
       @Column(name = "id", unique = true, nullable = false)
       @NotNull
       public int getId() {
       return this.id;
       }
      
       public void setId(int id) {
       this.id = id;
       }
      
       @Column(name = "name", nullable = false, length = 64)
       @NotNull
       @Length(min = 3, max = 64)
       public String getName() {
       return this.name;
       }
      
       public void setName(String name) {
       this.name = name;
       }
      
       @Column(name = "password", nullable = false, length = 16)
       @NotNull
       @Length(min = 4, max = 16)
       public String getPassword() {
       return this.password;
       }
      
       public void setPassword(String password) {
       this.password = password;
       }
      }


      Many thanks,
      Dustin