Chapter 6. Primary key mapping

Table of Contents

Natural versus Surrogate Ids
Assigned Id
Generated with Auto Strategy
Other Annotation Strategies
Composite Id
Equals and Hashcode
Other XML Id tags

A primary key in a database is a unique identifier, you can use as key to a data row. A primary key precisely identifies a row of a table.

Table 6.1. Example of a table having a unique Integer as primary key

Primary key Name

1

Jenny

2

Stephan

3

Sebastian


A primary key can consist of multiple column as well. In this case the combination of the columns must be unique.

Table 6.2. Example of a table having name and surname as primary key

Primary key - name Primary key – surname employedDate

Hennebrueder

Sebastian

March, 2nd 2005

Hennebrueder

Michael

April, 5th 2006

Jones

Jim

Mai, 8th 2007


Hibernate id

A primary key is used in Hibernate as well. It is called identifier (id) and identifies an object. Once a id is specified you cannot update it in Hibernate. Hibernate supports simple and composite ids. You can assign an id or use a generator to create an id. For example, a sequence generator, generates a unique Integer or Long value using a database sequence.

Natural versus Surrogate Ids

Natural Ids are ids, which uses real data to define a unique id. A id of a house can be city + street + house number. A surrogate id has nothing to do with the real data. It is artificial. It can be a unique number or a unique string. Do only use a natural id, if you are absolutely sure, that the columns included in this id, will never change. If in the example above the name of the street changes, you cannot update the name using Hibernate. Using SQL you will have to update the house table and all tables having a foreign relation to this table. A suitable case for a natural id could be a table holding ISO country codes:

Table 6.3. Example of a table having a natural primary key

Primary key – iso-code German name English name

en

Englisch

English

de

Deutsch

German


Keep in mind that even ISO codes do change over time.

See the discussion in the wikipedia as well: http://en.wikipedia.org/wiki/Surrogate_key

Source code. Source code for examples can be found in the projects mapping-examples-xml and mapping-examples-annotation in the Java package de.laliluna.primarykey.