Friday, January 8, 2010

Hibernate Id generation using sequence

Mapped classes must declare the primary key column of the database table. The element is used to define the mapping property to the primary key column.
We can specify the id with class to generate the auto increment value for this id property.
We can use hibernate generated sequence or data base sequence.

Hibernate sequence we can use the “increment” and “native” to use auto increment of the value.
We “increment” for numeric data to auto increment the data, “native” is also used same purpose but the hibernate will select the appropriate value based on the data base. For example on oracle native, increment as same effect which is used to get the value from “hibernate_sequence.NEXT_VALUE”.

To make the id has the database sequence then we need pass the sequence name with
element.



So while you are saving the object it is not required to the value for this property, since we set the value it overrides the value with the sequence generated value.
If we try to persist the object with the by setting the id value, it throws the exception entity cache is detached or not persistent object.
Note:- we can mix 2 strategies for the id property.