Sunday, May 15, 2011

Hibernate–Mapping the primary key or surrogate key and the natural key.

Primary key mapping

Primary key or surrogate key of an entity can be mapped in 2 ways : xml and annotations.

Xml way :

<id> tag is used to map primary key or surrogate key in hibernate, with <generator> for the field.

Annotation method:

For this @Id is used for the same. For auto generated use @GeneratedValue.

If the primary key and the Natural key for an entity is the same, which means we are assigning the value on our own, then we need to skip the <generator> tag in the xml file and @GeneratedValue when using hibernate.

Natural key mapping

For an entity with seperate natural key, we can use <natural-id> tag in xml and similar @NaturalId annotation.

Disclaimer

Java Jazzle is for learning and training only. Its not guaranteed that content published is correct. The risk from using it lies entirely with the user. Also the opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

About this blog

This is my tech blog. I write on this blog to save my searching stuff on google. It acts as my log of all the stuff I went through and saves my time, because I don't have to search again and again. Another reason for putting stuff on it was, when I am kind of free, it kind of kills it.