3 Replies Latest reply on Jan 28, 2009 10:43 PM by paulmkeogh

    Help needed with JPA please...

    paulmkeogh
      Hi,

      I have written a test that writes a record to the database twice. Everything is the same except for one element of the entity ID which I have defined as;

          @TableGenerator(name="CDR_GEN")
          @GeneratedValue(strategy=GenerationType.TABLE, generator="CDR_GEN")
          @Column(name="id", nullable=false)
          @NotNull
          public long getId() {
              return this.id;
          }
         
          public void setId(long id) {
              this.id = id;
          }

      I thought this is enough to uniquely construct the entity ID but I get;

      org.hibernate.NonUniqueObjectException: a different object with the same identifier value was already associated with the session

      When there is only one record, the ID is generated and makes it to the database just fine.

      So, clearly the generated ID is not making it into the session - googling suggests I can wrap a TX around every DB write or call flush() but I was wondering if theres an alternative ? Or am I way off in this approach ?

      Thanks,
        • 1. Re: Help needed with JPA please...
          qwertywin

              
              @Id
              @GeneratedValue(strategy = GenerationType.AUTO
              public long getId() {
                  return this.id;
              }
                   public void setId(long id) {
                  this.id = id;
              }



          should work

          • 2. Re: Help needed with JPA please...
            chawax

            I used TABLE generation type too and it works fine for me. One difference I see is that you didn't add @javax.persistence.Id annotation to your getId() method. Maybe you should try this ;)

            • 3. Re: Help needed with JPA please...
              paulmkeogh

              Thanks for the replies but I think the issue is a bit more complex.

              @Id in this case is in fact part of a composite primary key.

              And, according to this post on the Hibernate forum, you cannot use @GeneratedValue in an EmbeddedId class (the composite primary key).

              See http://forums.hibernate.org/viewtopic.php?p=2393944&sid=57b20ef2c7de6f6bcba632130987bc22

              So I guess its back to java.util.random and rolling my own IDs :-(