Pages Navigation Menu

Coding is much easier than you think

Auto Generate Primary key in Hibernate

 

 
In our early tutorials I have used @Id annotation to mark a particular field as primary key, this Primary key is used to fetch data via get or load method. And we set the value of primary key manually each time when we are about to create a new record.
 
In this article we shall learn to Auto Generate this Primary key value in Hibernate. Before getting into the above topic, let us have a discussion about Natural key and Surrogate key.
 

Natural Key

 
A natural key is a single column or set of columns which are made up of real data. When I say “real data” I mean data that has meaning and occurs naturally in the world of data. Some examples of natural keys values are Email id, Social Security Number etc.
 

Surrogate key

 
Surrogate key is “a system-generated value used to uniquely identify a row”. Its value is typically generated at run time right before the record is inserted into a table. Unlike natural keys, Surrogate key have no business meaning. Surrogate keys are commonly a numeric number.
 
So if we are having a natural key, it would make sense for us to provide the value via application, because it’s of business significance and we need to control its value.
 
But if it’s a Surrogate key then it’s not necessary that we have to provide it via our application. We can just ask hibernate to do the job for us, because it does not matter for us that what its value is going to be, we just need to make sure that its value had to be unique and not null.
 
To indicate hibernate to generate value for a primary key (Surrogate key) while inserting a new record in a table, we have to use @GeneratedValue. This annotation makes the column to be auto generated.
 
Example:
 

Entity Class

 

package entity;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "STUDENT")
public class StudentEntity {

	@Id
	@GeneratedValue
	@Column(name = "ID")
	private int id;

	@Column(name = "NAME")
	private String name;

	@Column(name = "DEPARTMENT")
	private String department;

	@Column(name = "COLLEGE")
	private String college;
	 
        //Create Getters and Setters
}

 

Hibernate Utility

 
Create the Main class to run the example.

public class HibernateUtil {

	public static void main(String[] args) {

	Configuration cf = new Configuration().configure("hibernate.cfg.xml");

	StandardServiceRegistryBuilder srb = new StandardServiceRegistryBuilder();
	srb.applySettings(cf.getProperties());
	ServiceRegistry sr = srb.build();
	SessionFactory sf = cf.buildSessionFactory(sr);

	Session session = sf.openSession();
	Transaction tx = session.beginTransaction();
	
	StudentEntity student1 = new StudentEntity();

	student1.setName("Jamil");
	student1.setDepartment("ECE");
	student1.setCollege("SKCET");
	
	StudentEntity student2 = new StudentEntity();

	student2.setName("Hp");
	student2.setDepartment("IT");
	student2.setCollege("SKCET");

	StudentEntity student3 = new StudentEntity();

	student3.setName("Lahr");
	student3.setDepartment("CSE");
	student3.setCollege("MCET");

        session.save(student1);
        session.save(student2);
        session.save(student3);

	tx.commit();
	session.close();
	sf.close();
	}
}

File hibernate.cfg.xml is same as in HelloWorld tutorial.
 

Database output

 
On running the above program, we get the following values in database.

 
Here the values in column ID is auto generated via @GeneratedValue.
 
In our next article we shall learn about configuring Composite Primary Keys In Hibernate.
 

Other Hibernate tutorial from our Blog