Monday, July 28, 2014

Mapping Id of Table to Class in Hibernate

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.

More write-ups on Hibernate

No comments:

Post a Comment