Primary key in Hibernate
In relational databases, there is an important concept of primary keys. In this tutorial, we will learn the use of Primary keys with hibernate. In the previous tutorials, we have defined the primary key but we have not discussed it yet.
Hibernate Annotation
The annotation that hibernates provides for defining an attribute of an entity as a primary key is @Id. In the previous tutorial, we have defined the Id attribute as a primary key and generate its getters and setters to access it because this attribute is private. @Id creates a column in the table of the database which well be marked as the Primary key. Now this created column has unique values in it.
Natural key and surrogate key
We have two kinds of keys a natural key and surrogate key. Natural keys are those keys that exist in the real world like registration numbers etc and surrogate keys are those that do not exist in the real world and we make them by ourselves. We are using the natural key we have to provide its value because of its real world significance. By providing the value we have an option of controlling it while in the case of the surrogate key we assign this job to hibernate and hibernate then maintain a primary key for us and we don’t have to worry for its uniqueness. The syntax for surrogate key Annotation is simply using @GeneratedValue with @Id. In the case of @GeneratedValue, we don’t have to set id by our self in the main class.
Hibernate provides us this feature in its “javax.persistence.GeneratedValue” package.
Now If we try to save two users in the databases without passing the Id in the “HibernateMain” then due to @GeneratedValue Annotation hibernate will automatically generate the surrogate key.
The final code for HibernateMain and User Details will look like this and hibernate.cfg.xml will remains the same.
HibernateMain.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
package org.uzair.hibernate; import java.util.Date; import org.beginnersheap.uzair.dto.UserDetails; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; public class HibernateMain { public static void main(String[] args) { UserDetails objectUser = new UserDetails(); objectUser.setUserName("FirstUserName"); UserDetails objectUser2 = new UserDetails(); objectUser2.setUserName("SecondUserName"); SessionFactory factory = new Configuration().configure().buildSessionFactory(); Session session = factory.openSession(); session.beginTransaction(); session.save(objectUser); session.save(objectUser2); session.getTransaction().commit(); //Reterive UserObject using Hibernate API session.close(); session = factory.openSession(); objectUser=null; objectUser2=null; session.beginTransaction(); objectUser = (UserDetails) session.get(UserDetails.class, 1); objectUser2 = (UserDetails) session.get(UserDetails.class, 2); System.out.println("UserName : "+objectUser.getUserName()); System.out.println("UserName : "+objectUser2.getUserName()); } } |
UserDetails.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
package org.beginnersheap.uzair.dto; import java.util.Date; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Table; import javax.persistence.Id; @Entity @Table (name="NewTableName") public class UserDetails { @Id @GeneratedValue private int userId; private String userName; private Date joinedDate; private String Address; private String description; public Date getJoinedDate() { return joinedDate; } public void setJoinedDate(Date joinedDate) { this.joinedDate = joinedDate; } public String getAddress() { return Address; } public void setAddress(String address) { Address = address; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public int getUserId() { return userId; } public void setUserId(int userId) { this.userId = userId; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } } |
Test Run
In Eclipse we can also run our java application with short keys, Alt+Shift+X , j
Console
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
<strong>Hibernate: drop table if exists NewTableName cascade </strong> Sep 25, 2016 7:04:19 PM org.hibernate.resource.transaction.backend.jdbc.internal.DdlTransactionIsolatorNonJtaImpl getIsolatedConnection INFO: HHH10001501: Connection obtained from JdbcConnectionAccess [org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess@655f7ea] for (non-JTA) DDL execution was not in auto-commit mode; the Connection 'local transaction' will be committed and the Connection will be set into auto-commit mode. <strong>Hibernate: drop sequence if exists hibernate_sequence Hibernate: create sequence hibernate_sequence start 1 increment 1 </strong> Sep 25, 2016 7:04:19 PM org.hibernate.resource.transaction.backend.jdbc.internal.DdlTransactionIsolatorNonJtaImpl getIsolatedConnection INFO: HHH10001501: Connection obtained from JdbcConnectionAccess [org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess@6da00fb9] for (non-JTA) DDL execution was not in auto-commit mode; the Connection 'local transaction' will be committed and the Connection will be set into auto-commit mode. <strong>Hibernate: create table NewTableName (userId int4 not null, Address varchar(255), description varchar(255), joinedDate timestamp, userName varchar(255), primary key (userId)) </strong> Sep 25, 2016 7:04:19 PM org.hibernate.tool.schema.internal.SchemaCreatorImpl applyImportSources INFO: HHH000476: Executing import script 'org.hibernate.tool.schema.internal.exec.ScriptSourceInputNonExistentImpl@75b25825' <strong>Hibernate: select nextval ('hibernate_sequence') Hibernate: select nextval ('hibernate_sequence') Hibernate: insert into NewTableName (Address, description, joinedDate, userName, userId) values (?, ?, ?, ?, ?) Hibernate: insert into NewTableName (Address, description, joinedDate, userName, userId) values (?, ?, ?, ?, ?) Hibernate: select userdetail0_.userId as userId1_0_0_, userdetail0_.Address as Address2_0_0_, userdetail0_.description as descript3_0_0_, userdetail0_.joinedDate as joinedDa4_0_0_, userdetail0_.userName as userName5_0_0_ from NewTableName userdetail0_ where userdetail0_.userId=? Hibernate: select userdetail0_.userId as userId1_0_0_, userdetail0_.Address as Address2_0_0_, userdetail0_.description as descript3_0_0_, userdetail0_.joinedDate as joinedDa4_0_0_, userdetail0_.userName as userName5_0_0_ from NewTableName userdetail0_ where userdetail0_.userId=? UserName : FirstUserName UserName : SecondUserName</strong> |
This console tells us that hibernate first drops the table if exists because we have set “hbm2ddl.auto” to create. After that hibernate will create the new table and for inserting the records in this table it will auto generate the sequence for the id by finding the last id and increment it by one.
We can also define various strategies for the Generated Value hibernate provides us these Generation Types.
- Auto : It’s up to hibernate which strategy to use in order to generate Primary Keys
- Identity: Hibernate us Identity Columns as Primary Keys. Not every database supports this feature.
- Sequence: Hibernate has Sequence object that will be used to maintain unique Primary Keys
- Table: Hibernate will create a separate Table to maintain a unique Primary Key.
Default as AUTO.
Summary:
In this tutorial, we have accomplished following things.
- How to create Primary Keys in Hibernate.
- How to use Generate Values Annotation.
- What options do we have with Generate Value Annotation.
Hope that you like this tutorial. Stay tuned for more upcoming tutorials. Stay Blessed!
About Author: Uzair Ahmed Khan is Technical Content Writer, Computer Software Blogger, and Software Engineer. He has a keen eye on Java Technologies other Related Developments.