Nearby lessons

11 of 19

Hibernate - Primary Key Generation Strategies

📌 What You Will Learn
  • Understand Hibernate - Primary Key Generation Strategies
  • See working code examples
  • Learn from common mistakes and Q&A

Learn Hibernate - Primary Key Generation Strategies step by step — simple explanations, complete programs with their output, common beginner mistakes, and exam-style MCQs.

Primary Key Generation Strategies — Employee.java

Example:

Example01
JCode Cell
1 
2package com.durgasoft.hbn.pojo;
3 
4public class Employee {
5private int eno;
6private String ename;
7private float esal;
8private String eaddr;
9 
10public int getEno() {
11return eno;
12}
13public void setEno(int eno) {
14this.eno = eno;
15}
16public String getEname() {
17return ename;
18}
19public void setEname(String ename) {
20this.ename = ename;
21}
22public float getEsal() {
23return esal;
24}
25public void setEsal(float esal) {
26this.esal = esal;
27}
28public String getEaddr() {
29return eaddr;
30}
31public void setEaddr(String eaddr) {
32this.eaddr = eaddr;
33}
34 
35 
36}
37

Primary Key Generation Strategies — Employee.hbm.xml

Example02
JCode Cell
1 
2<?xml version="1.0" encoding="UTF-8"?>
3<!DOCTYPE hibernate-mapping PUBLIC
4"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
5"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
6<hibernate-mapping>
7<class name="com.durgasoft.hbn.pojo.Employee" table="emp1">
8 <id name="eno"/>
9 <property name="ename"/>
10 <property name="esal"/>
11<property name="eaddr"/>
12</class>
13</hibernate-mapping>
14

Primary Key Generation Strategies — hibernate.cfg.xml

Example03
JCode Cell
1 
2<?xml version="1.0" encoding="UTF-8"?>
3<!DOCTYPE hibernate-configuration PUBLIC
4"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
5"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
6<hibernate-configuration>
7<session-factory>
8<property name="connection.driver_Class">oracle.jdbc.OracleDriver</property>
9<property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>
10<property name="connection.username">system</property>
11<property name="connection.password">durga</property>
12<property name="hibernate.dialect">org.hibernate.dialect.OracleDialect</property>
13<property name="show_sql">true</property>
14<mapping resource="Employee.hbm.xml"/>
15</session-factory>
16</hibernate-configuration>
17

Primary Key Generation Strategies — ClientApp.java

Example04
JCode Cell
1 
2package com.durgasoft.hbn.test;
3 
4import org.hibernate.Session;
5import org.hibernate.SessionFactory;
6import org.hibernate.boot.registry.StandardServiceRegistry;
7import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
8import org.hibernate.cfg.Configuration;
9 
10import com.durgasoft.hbn.pojo.Employee;
11 
12public class ClientApp {
13 
14public static void main(String[] args)throws Exception {
15Configuration cfg = new Configuration();
16cfg.configure();
17StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder();
18builder = builder.applySettings(cfg.getProperties());
19StandardServiceRegistry registry = builder.build();
20SessionFactory sessionFactory = cfg.buildSessionFactory(registry);
21Session session = sessionFactory.openSession();
22Employee emp = (Employee)session.get("com.durgasoft.hbn.pojo.Employee", 111);
23if(emp == null) {
24 System.out.println("Emnployee Not Existed");
25}else {
26 System.out.println("Employee Details");
27 System.out.println("---------------------");
28 System.out.println("Employee Number :"+emp.getEno());
29 System.out.println("Employee Name :"+emp.getEname());
30 System.out.println("Employee Salary :"+emp.getEsal());
31 System.out.println("Employee Address :"+emp.getEaddr());
32}
33session.close();
34sessionFactory.close();
35}
36 
37}
38

Primary Key Generation Algorithms in Hibernate

 Primary key is single column or Collection of columns in a table to recognize the records individually.

 In Database applications, to perform the database operations like retriving a record, updating a record, deleting a record,....we need primary key and its value.

 In Database applications, we are unable to give option to the users to enter primary key values , because, there is no guarantee for the data entered by the users whether it is unique data or not, but, in Database tables only unique values are accepted by primary key columns.

 To give guarantee for uniqueness in primary key values we have to use Primary key generation algorithms.

 Almost all the Persistence mechanisms like Hibernate, JPA, Open JPA, Toplink,.... are having their own implementation for primary key generation algorithms.

Hibernate has provided support for the following primary key generation algorithms inorder to generate primary key values.

  • assigned
  • increment
  • sequence
  • identity
  • hilo
  • native.
  • seq-hilo
  • select
  • UUID
  • GUID
  • foreign

Hibernate has represented all the above primary key generation algorithms in the form of a set of predefined classes provided in

"org.hiberante.id" package.

If we want to use any of the above algorithms in Hibernate applications then we have to configure that algorithms in hibernate mapping file by using the following tags.

  • <hibernate-mapping>
  • <class name="--" table="--">
  • <id name="--" column="--">
  • <generator class="--">
  • <param name="--">value</param>
  • </generator>
  • </id>
  • </class>
  • </hibernate-mapping>

 Where <generator> tag will represent a particular primary key generation algorithm.

 Where "class" attribute in <generator> tag will take either short name or Fully qualified name of Generator class.

 Where <param> tag will provide single input parameter to the Primary key generator inorder to generate primary key value.

 Where "name" attribute in <param> tag will take parameter name , here we have to provide parameter value as body to the <param> tag.

assigned

This algorithm is default primary key generation algorithm in hibernate applications, it will not required configurations in mapping file. This algorithm will not have its own mechanism to generate primary key value , it will request to Client Application to provide primary key value explicitly. This algorithm is able to support for any type of primary key values like short, int, long, String,..... This alg is supported by almost all the databases like Oracle, MySQL, DB2, ...... This alg is not required any input parameter. This alg is represented by Hibernate in the form of a predefined class "org.hibernate.id.Assigned".

Example06
JCode Cell
1 
2<class name="Employee" table="emp1">
3<id name="eno" column="ENO">
4<generator class="assigned"/>
5</id>
6----
7</class>
8

increment

This primary key generation algorithm is able to generate primary key value by incrementing max value of the primary key column.

New_Val = max(PK_Column)+1 This alg is able to generate primary key values of the data types like short, int, long,... This alg is not required any input parameter to generate primary key values. This alg is supported by almost all the databases which are supporting numeric values as Primary key values. This alg is representned by Hibernate Software in the form of a short name "increment" and in the form of a predefined class like "org.hibernate.id.IncrementGenerator".

Example07
JCode Cell
1 
2<hibernate-mapping>
3<class name="Employee" table="emp1">
4<id name="eno" column="ENO">
5<generator class="org.hibernate.id.IncrementGenerator"/>
6</id>
7----
8</class>
9</hibernate-mapping>
10

sequence

This primary key generation algorithm is able to generate primary key value on the basis of the sequence provided by the underlying Database. This alg is able to generate primary key values of the data types like short, int, long,... This alg required "sequence" input parameter with the sequence name as value inorder to generate primary key value. If we have not provided any sequence name as input parameter then this alg is able to take "hibernate_sequence" as default sequence name, here developers must create "hibernate_sequence" in database explicitly. This alg is supported by almost all the databases which are supporting sequences like Oracle, DB2,.... This alg is represented by Hibernate Software in the form of a short name like "sequence" and in the form of a predefined class like "org.hibernate.id.SequenceGenerator".

EX:

In Database

SQL>create sequence my_sequence increment by 5; SQL>commit;

In mapping File

  • <hibernate-mapping>
  • <class name="Employee" table="emp1">
  • <id name="eno" column="ENO">
  • <generator class="sequence">
  • <param name="sequence">my_sequence</param>
  • </generator>
  • </id>
  • </class>
  • </hibernate-mapping>

Note: If we dont want to use explicit sequence then we must create default sequence in database , that is, "hibernate_sequence".

SQL>create sequence hibernate_sequence increment by 5;

identity

This alg is able to generate primary key values on the basis on the underlying database table provided identity column. Note: Identity column is a primary key Column with "auto_increment" capability. This alg is able to provide the primary key values of the data types like short, int, long,.... This alg is not required any input parameter. This alg is supported by almost all the databases which are supporting Identity column. EX: MySQL. To represent this alg, Hibernate has provided "identity" as short name and "org.hibernate.id.IdentityGenerator" as predefined class.

EX:

IN MySQL database

sql>create table emp1(ENO primary key auto_increment, ENAME char(10), ESAL float, EADDR char(10));

IN Mapping File

  • <hibernate-mapping>
  • <class name="Employee" table="emp1">
  • <id name="eno" column="ENO">
  • <generator class="identity"/>
  • </id>
  • </class>
  • </hibernate-mapping>

hilo[High-Low]

This alg is able to generate primary key value by getting high value from a particular global resource and low value from mapping file.

Note: Global resource is a particular table with a column in the same database. This alg is able to generate primary key values of the data types like short, int, long,.... To represent this alg. Hibernate software has provides a seperate short in the form of "hilo" and a seperate predefined class in the form of "org.hibernate.id.TableHiLoGenerator". This alg is supported by almost all the databases like Oracle, MySQL,.... To generate primary key value this alg will take the following three parameters.

  • table: Global resource name , that is, a table name which provides high value.
  • column:column name existed in Global Resource to manage high value.
  • max_lo:It will provide low value .

Note: If we have not provided Global resources parameters like table and column in mapping file then Hibernate Software will take high value from default global resource table "hibernate_unique_key" and column "next_hi".

Example14
JCode Cell
1 
2<hibernate-mapping>
3<class name="Employee" table="emp1">
4<id name="eno" column="ENO">
5<generator class="hilo">
6<param name="table>my_table</param>
7<param name="column">my_column</param>
8<param name="max_lo">10</param>
9</generator>
10</id>
11----
12</class>
13</hibernate-mapping>
14In Database:
15SQL>create table my_table(my_column number primary key);
16SQL>insert into my_table values(100);
17SQL>commit;
18

hilo[High-Low]

Note: If we want to use default table name and column instead of my_table and my_column then we have to remove "table" and "column" parameters in mapping file and provide the following in Database.

SQL>create table hibernate_unique_key(next_hi number primary key); SQL>insert into hibernate_unique_key values(100); SQL>commit;

native

This alg is able to generate primary key value by selecting a particular primary key generation alg depending on the database which we used. This alg is not having its own alg to generate primary key value. It will select "SequenceGenerator" alg if we are using Oracle database, "IdentityGenerator" alg if we are using MySQL database and "TableHiLoGenerator" if we are using some other database which is not supporting SequenceGenerator and IdentityGenerator. This Primary key generator is able to generate primary key values of the data types like short, int, long,... This primary key generator is supported by almost all the databases. To represent this mechanism, Hibernate has provided a short name in the form of "native", Hibernate has not provided any predefined class. This alg is able to take parameters on the basis of the selected primary key generator depending on the database. If it is using "SequenceGenerator" then we must provide "sequence" parameter. If it is using TableHiloGenerator then we have to provide "table", "column", "max_lo" parameters.

Example16
JCode Cell
1 
2<hibernate-mapping>
3<class name="Employee" table="emp1">
4<id name="eno" column="ENO">
5<generator class="native">
6---provide parameters depending on requirement---
7</generator>
8</id>
9</class>
10</hibernate-mapping>
11

seq-hilo

This alg is able to generate primary key values on the basis of the sequence value provided by the underlying database and the mapping file provided max_lo property valye. This alg is almost all same as HiLo alg but in "seqhilo" alg we will get sequence vaue inplace of the high value from Global resouce. This alg is able to generate primary key values of the data types like short, int and long. This alg is represented by Hibernate software in the form a short name like "seqhilo" and a predefined class name like "org.hibernate.id.SequenceHiLoGenerator". This alg is supported by almost all the databases which are supporting sequences internally. This alg is required the following two input parameters.

  • sequence: It will take sequence name provided by Database.
  • max_lo : It will provide low value.

Note: If we have not provided "sequence" input parameter then hibernate software will search for the default sequence name like "hibernate_sequence".

Example17
JCode Cell
1 
2<hibernate-mapping>
3<class name="Employee" table="emp1">
4<id name="eno" column="ENO">
5<generator class="seqhilo">
6 <param name="sequence">my_sequence</param>
7 <param name="max_lo">10</param>
8</generator>
9</id>
10----
11</class>
12</hibernate-mapping>
13

select

This alg is able to generate promary key values on the basis of the underlying database provided triggers. This alg is able to provide primary key values of the data types like short, int and long. This alg is represented by Hibernate software in the form of a short name like "select" and a predefined class name "org.hibernate.id.SelectGenerator". This alg may take input parameters which are related to triggers. This alg is supported by almost all the databases which are supporting triggers.

Example18
JCode Cell
1 
2<hibernate-mapping>
3<class name="Employee" table="emp1">
4<id name="eno" column="ENO">
5<generator class="select">
6--- parameters related to triggers----
7</generator>
8</id>
9-----
10</class>
11</hibernate-mapping>
12

UUID[Unicersal Unique Identity]

This alg is able to generate primary key value on the basis of System IP-Address , JVM Startup time, Current System time,.... factors. This alg is able to generate primary key value in the form of 32 bit hexa decimal value. This alg is able to generate primary key value of the data type like String. This alg is represented by Hibernate software in the form of a short name "uuid" and a predefined class name "org.hibernate.id.UUIDHexGenerator". This alg is supported by almost all the databases which are supporting String type primary key values. This alg is not required any input parameters, but, it must required "varchar" type primary key column with 32 column size minimum in database table.

Example19
JCode Cell
1 
2<hibernate-mapping>
3<class name="Employee" table="emp1">
4<id name="eno" column="ENO" type="string">
5<generator class="org.hibernate.id.UUIDHexGenerator"/>
6</id>
7----
8</class>
9</hibernate-mapping>
10GUID This alg is able to generate primary key values on the basis of the underlying database provided identity column with String type.
11

UUID[Unicersal Unique Identity]

This alg is represented in the form of a predefined class org.hibernate.id.GUIDGenerator and in the form of a short name like "guid". This alg is not requires any input parameters to generate primary values. This alg is supported by the databases which are supporting string type id columns.

Example20
JCode Cell
1 
2<hibernate-mapping>
3<class name="Employee" table="emp1">
4<id name="eno" column="ENO">
5<generator class="org.hibernate.id.GUIDGenerator"/>
6</id>
7----
8</class>
9</hibernate-mapping>
10foreign This primary key generation alg is able to generate primary key values on the basis of the foreign key of the present table.
11

UUID[Unicersal Unique Identity]

This alg is able to generate primary key values of the data types like short, int and long. This alg is not required any input parameters to generate primary key values. This alg is represented by Hibernate software in the form of a short name "foreign" and in the form of a predefined class like "org.hibernate.id.ForeignGenerator".

Example21
JCode Cell
1 
2<hibernate-mapping>
3<class name="Employee" table="emp1">
4<id name="eno" column="ENO">
5<generator class="org.hibernate.id.ForeignGenerator"/>
6</id>
7----
8</class>
9</hibernate-mapping>
10

Annotations Support for Primary Key Generation Alg — Employee.java

Hibernate has provided annotations for almost all the primary key generation alg in the form of javax.persistence package and org.hibernate.annotation package.

To provide annotations for primary key generation alg javax.persistence package has provided the following annotations.

 @GeneratedValue(--,--)  @SequenceGenerator(--)  @TableGenerator(--) --- ---

To provide a particular primary key generation alg in hibernate applications, we have to use "strategy" member in @GeneratedValue(-) annotation, it will take either of the following constants from "GenerationType" Enum.

  • IDENTITY
  • SEQUENCE
  • TABLE
  • AUTO
  • IDENTITY: This value of GenerationType enum will represent IdentityGenerator or "identity" primary key generation algorithm to generate primary key value on the basis of the underlying database provided identity column.

EX: Employee.java

  • @Entity
  • @Table(name="emp1")
  • public class Employee {
  • @Id
  • @Column(name="ENO")
  • @GeneratedValue(strategy=GenerationType.IDENTITY)
  • private int eno;
  • @Column(name="ENAME")
  • private String ename;
  • @Column(name="ESAL")
  • private float esal;
  • @Column(name="EADDR")
  • private String eaddr;
  • setXXX() and getXXX()
  • SEQUENCE : This constant from GenerationType enum is able to represent SequenceGenerator or "sequence" primary key generation algorithm inorder to gtenerate primary key value on the basis of the sequence which we defined in database.

To configure "sequence" name we have to use "@SequenceGenerator" annotation with the following members.

  • name: It will take logical name of the @SequenceGenerator.
  • sequenceName: it will take "sequence" name provided by underlying database.

To apply @SequenceGenerator to @GeneratedValue annotation we have to use "generator" member in "@GeneratedValue" annotation. EX: Employee.java

  • @Entity
  • @Table(name="emp1")
  • public class Employee {
  • @Id
  • @Column(name="ENO")
  • @SequenceGenerator(name="seqGen", sequenceName="my_sequence")
  • @GeneratedValue(strategy=GenerationType.SEQUENCE, generator="seqGen")
  • private int eno;
  • @Column(name="ENAME")
  • private String ename;
  • @Column(name="ESAL")
  • private float esal;
  • @Column(name="EADDR")
  • private String eaddr;
  • setXXX() and getXXX()

Note: In the above example , if we remove @SequenceGenerator annotation and "generator" member in @GeneratedValue annotation then Hibernate software will search for the default sequence name like "hibernate_sequence" in the database.

  • TABLE: This constant from GenerationType enum is able to represent HiLo Primary key generation alg inorder to generate primary key values on the basis of Global resource. To configure Global resource table and its properties we have to use @TableGenerator() annotation with the following members.
  • name: it will take logical name to the @TableGenerator
  • pkColumnName: it will take primary key column name of the Global resource table.
  • pkColumnValue: It will take initial value to the primary key column in global resource

table.

  • valueColumnName: it will take a column name which is generating our required

primary key value.

  • table: it will take Global resource table name.

To apply @TableGenerator annotation to @GeneratedValue annotation we have to use "generator" member in @GeneratedValue annotation.

EX: Employee.java

  • @Entity
  • @Table(name="emp1")
  • public class Employee {
  • @Id
  • @Column(name="ENO")
  • @TableGenerator(name="tableGen",
  • table="my_table",
  • pkColumnName="id",
  • pkColumnValue="10", valueColumnName="next_hi")
  • @GeneratedValue(strategy=GenerationType.TABLE, generator="table

Gen")

  • private int eno;
  • @Column(name="ENAME")
  • private String ename;
  • @Column(name="ESAL")
  • private float esal;
  • @Column(name="EADDR")
  • private String eaddr;
  • setXXX() and getXXX()
  • AUTO: This constant from GenerationType enum is able to represent "native" primary key generation alg inorder to generate primary key value by selecting either sequence or identity or hilo primary key generation algorithms on the basis of the under lying database.

Note: Depending on the database or depending on the internal primary key generation alg we have to provide4 input parameters by using @SequenceGenerator() or @TableGenerator() annotations.

EX: Employee.java

  • @Entity
  • @Table(name="emp1")
  • public class Employee {
  • @Id
  • @Column(name="ENO")
  • @SequenceGenerator(name="seqGen", sequenceName="my_sequence")
  • @GeneratedValue(strategy=GenerationType.AUTO, generator="seqGen")
  • private int eno;
  • @Column(name="ENAME")
  • private String ename;
  • @Column(name="ESAL")
  • private float esal;
  • @Column(name="EADDR")
  • private String eaddr;
  • setXXX() and getXXX()

Note: For the remaining primary key generation alg , Hibernate has provided the following annotation in org.hibernate.annotation package.

@GenericGenerator(name="--", strategy="--",parameters={...}) @GeneratedValue(generator="--")

  • name: It will take logical name to @GenericGenerator
  • strategy: It will take short name of the primary key generation alg.
  • parameters: It will take array of @Parameter() with the following members to declare

parameter values.

  • name: it will take param name.
  • value: It will take param value.

EX:Employee.java

  • @Entity
  • @Table(name="emp1")
  • public class Employee{
  • @Id
  • @Column(name="ENO")
  • @GenericGenerator(name="incGen" strategy="increment")
  • @GeneratedValue(generator="incGen")
  • private int eno;

EXAMPLE:

Example22
JCode Cell
1 
2package com.durgasoft.hbn.pojo;
3 
4import javax.persistence.Column;
5import javax.persistence.Entity;
6import javax.persistence.GeneratedValue;
7import javax.persistence.GenerationType;
8import javax.persistence.Id;
9import javax.persistence.SequenceGenerator;
10
📝 Key Takeaways
  • Key ideas of Hibernate - Primary Key Generation Strategies explained simply
  • Ready-to-use code examples
  • Exam-style questions at the end