-->
These old forums are deprecated now and set to read-only. We are waiting for you on our new forums!
More modern, Discourse-based and with GitHub/Google/Twitter authentication built-in.

All times are UTC - 5 hours [ DST ]



Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 3 posts ] 
Author Message
 Post subject: When does hibernate generate IDs
PostPosted: Tue Jul 08, 2014 3:08 pm 
Newbie

Joined: Tue Jul 08, 2014 2:49 pm
Posts: 2
Lets say I have the following code:
Code:
@Entity
public class Person {
   
   @Id
   @GeneratedValue(strategy=GenerationType.AUTO)
   private Long id;
   
   private String name;
   
   public Long getId() {
      return id;
   }
   public void setId(Long id) {
      this.id = id;
   }

   public boolean equals(Object other) {
      if(other instanceof Person)  {
         return id.equals(((Person) other).getId());
      } else {
                        return false;
                }
   }

   public static void main(String[] args) {
      Person p1 = new Person();
      Person p2 = new Person();
      System.out.println(p1.equals(p2));  //this throws a null pointer exception
   }

}


I was wondering when hibernate assigns the ID field to the Person object, because I'd like to use the @Id as the primary field for the equals method but as the code is right now, I get a null pointer exception. Any insights would be helpful. Thanks!


Top
 Profile  
 
 Post subject: Re: When does hibernate generate IDs
PostPosted: Tue Jul 08, 2014 3:16 pm 
Hibernate Team
Hibernate Team

Joined: Fri Oct 05, 2007 4:47 pm
Posts: 2536
Location: Third rock from the Sun
The ID is assigned when the entity is persisted / saved. Not a good idea to base the equals implementation on it, unless you always persist the entity as soon as you created it (which is usually a very nice pattern). Consider the entity is only actually written to the database then the transaction commits, so there is no reason to postpone saving it.

_________________
Sanne
http://in.relation.to/


Top
 Profile  
 
 Post subject: Re: When does hibernate generate IDs
PostPosted: Wed Jul 09, 2014 10:00 am 
Newbie

Joined: Tue Jul 08, 2014 2:49 pm
Posts: 2
Okay great I'll give that a try thanks for the response!


Top
 Profile  
 
Display posts from previous:  Sort by  
Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 3 posts ] 

All times are UTC - 5 hours [ DST ]


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum

Search for:
© Copyright 2014, Red Hat Inc. All rights reserved. JBoss and Hibernate are registered trademarks and servicemarks of Red Hat, Inc.