Sunday, May 15, 2011

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

For clearer terminology on various keys, refer this article.

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.

No comments:

Post a Comment