Tuesday, March 17, 2015

Natural key vs Surrogate key

This is very common in primary key selection.
Let's take an example to have a better understanding and for ease of explaining.

if we take list of people, for more precisely take students.
So we have student list. every student has a email. thus email cannot be duplicate. So we can use email as a unique identifier for a student. In a scenario like this email is a natural key for student.

Surrogate key on the other hand does not have any relevance to the business and but where need to have a unique key to identify the object, we define surrogate key.
eg : serial number, id for any table(student_id, group_id)

When we have Surrogate key we have problem of maintaining uniqueness.
Hibernate has given solution, actually made our lives easy with making sure hibernate layer generate unique ids.
eg : User object has user_id as primary key

@Id
@GeneratedValue
private int userId;

this will take care of the surrogate key , userId and generarate unique value for userId.

Further hibernate has given us the option of using a strategy for generated value.


@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name = "USER_ID")
private int userId;

we have 4 strategy types

GenerationType.AUTO = either identity column, sequence or table depending on the underlying DB
GenerationType.IDENTITY=  identity column
GenerationType.SEQUENCE =  sequence
GenerationType.TABLE - hibernate will make a separate table and use that.table holding the id

http://docs.jboss.org/hibernate/annotations/3.5/reference/en/html_single/#entity-mapping-identifier


No comments:

Post a Comment