Win a copy of The Little Book of Impediments (e-book only) this week in the Agile and Other Processes forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Persist Method

 
Nikhil Jain
Ranch Hand
Posts: 392
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How do we get the generated primary key after the object is persisted.

public void storeEmployee(String name, int age) {
Employee emp = new Employee();
emp.setName(name);
emp.setAge(age);
em.persist(emp);
em.flush();
System.out.println(emp.getId()); ---> ///Always prints out 0
}
 
Nikhil Jain
Ranch Hand
Posts: 392
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It working I was not adding @GeneratedValue

@Id
@GeneratedValue
public int getId() {
return id;
}

But when @GeneratedValue was not added, the code did not generate any error. The entires were persisting in database. But when I used to call getId(), I used to get 0!!! ??
 
Joe Harry
Ranch Hand
Posts: 10128
3
Eclipse IDE Mac PPC Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Anu Tilwalli:
It working I was not adding @GeneratedValue

@Id
@GeneratedValue
public int getId() {
return id;
}

But when @GeneratedValue was not added, the code did not generate any error. The entires were persisting in database. But when I used to call getId(), I used to get 0!!! ??


How did your mapping file look like? It persisted because of what you have given in your mapping file for the id column. The default value for an int is 0 and since you missed out the annotation, it simply did not run any query to fetch you the correct id.
 
Christophe Verré
Sheriff
Posts: 14691
16
Eclipse IDE Ubuntu VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Remember SCJP, where you learned that member variables had implicit values ?
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic