Share |
Hibernate Mapping Identity        
Print

Hibernate Mapping Identity

Identity of an object is the property which is mapped to primary key of the row in the database. The id of the entity is mapped by @Id annotation
@Entity @Table(name="Student") public class Student { //Id will correspond the primary key in the database private Long id; protected String name; ... //Id - Represents that it is a primary key column //GeneratedValue - How the key to be generated //column - Column to which this property is mapped @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name="STUDENT_ID") public Long getId() { return id; } public void setId(Long id) { this.id = id; } ...

Hibernate supports many identifier generation strategy which supports all the major databases

Hibernate does not allows to change the Id once it has been set. It throws an exception if an attempt is made
student = new Student(); Long studentId = (Long)session.save(student); //student.setId(80L); - This will throw an exception


Right now JPA supports limited identifier generation strategy. So if the hibernate generation strategies need to be employed than do as follows:
@Entity @org.hibernate.annotations.GenericGenerator( name="hibernate-native", strategy="native") public class Student{ private Long id; protected String name; @Id @GeneratedValue(generator="hibernate-native") @Column(name="STUDENT_ID") public Long getId() { return id; }


It's possible to write one's own identifier generation strategy by implementing IdentifierGenerator interface. However try to use one of the existing generator as Hibernate already has very rich identifier generators.


Back to Hibernate Index
Back To Java Home
Back To Home

Post new comment

Click for Help
BoldItalicUnderlineStrikethroughExternal LinkSmileys
Anti-Bot verification code: Random Image
Post new comment