tags:

views:

14

answers:

2

Hi,

I have a class which is mapped to a table using the hibernate notations of auto increment. This class works fine when I set values and update this to the database and I get a correct updated value in the table.

But the issue is when I create a new object of this class and try to get the id, it returns me a 0 instead of the auto_incremented id.

The code of the class is

@Entity(name="babies")
public class Baby implements DBHelper{

 private int babyID;


 @Id 
 @Column(name="babyID", unique=true, nullable= false)
 @GeneratedValue(strategy = GenerationType.AUTO)
 public int getBabyID() {
  return babyID;
 }
 public void setBabyID(int babyID) {
  this.babyID = babyID;
 }
}

The code I use to get the persistent value is

Baby baby = new Baby(); System.out.println("BABY ID = "+baby.getBabyID());

This returns me a

BABY ID = 0

Any pointers would be appreciated.

Thanks, Sana.

+1  A: 

The ID is set by hibernate when object is saved and became persistable.

The annotation are only informing hibernate, how he should behave with class, property, method that annotation refer to.

Another thing if You have current id value how hibernate, would be able to recognize that he should insert or only update that value.

So this is normal expected behavior.

Vash
+1  A: 

Hibernate only generates the id after an entity becomes persistent, ie after you have saved it to the database. Before this the object is in the transient state. Here is an article about the Hibernate object states and lifecycle

mR_fr0g
sheesh! Anyway to work around without using SQL to get hte maximum content from the tbale?
Sana
Using criteria and projections You can easily do that. DetachedCriteria.forClass(Baby.class).add(setProjection(Property.forName("babyID").max());
Vash