How to create primary key using hibernate?

Showing Answers 1 - 9 of 9 Answers


  • Oct 25th, 2006

In your hbm.xml file use field.this field create a primary key for u .

  Was this answer useful?  Yes

Sachin Yadav

  • Feb 10th, 2007

id field in hbm.xml file is used to specify the primary key in database. We also use generator to specify the way primary key is generated to the database. For example
< id name="testId" type="string" >
< column name="testColumn" length="40" / >
< generator class="increment" / >
< /id >
here the primary key field name in datbase is testColumn and it will autonmatically incremented by one as the generator is specified as increment.

Sony v George

  • Apr 5th, 2007

In .hbm file there is a tag called id, there we mention the primary key.

 <class name="pojo1" table="pojo1" discriminator-value="s">
 <id name="empid" type="string" >
  <generator class="assigned"/>

Here Id ="empid", that will act as primary key of the table "pojo1"


  • Dec 28th, 2007

We can also specify primary key using annotations in the POJO using:

@javax.persistence.Id before the appropriate field in POJO with @Column


  Was this answer useful?  Yes


  • Jul 29th, 2008

Ccreate primary key? Not sure but you can defined it in the hbm file by specifying the field with the primary column in the db.

  Was this answer useful?  Yes

First you have to do is when you are creating table itself you have to give the primary key for any one of the column and then in the hibernate take hbm file  in that there is a tag like <id> in that tag u have to give the name of the column in table which is considered as primary key and also give the name of the property in pojo class which is considered as primary key.So the name of the property which is placed in <id> is considered as primary key by hibernate.

  Was this answer useful?  Yes


  • Jul 13th, 2012

In hibernate mapping file

  1. .hbm.xml add <id> under <class>

  2. <class name="class name" table="table name">

  3.    <id name="pojo variable name" column="table column name"/>//primarykey mapping

  4.    <property name="pojo variable name" column="table column name/>//non-primarykey mapping

  5. </class>

  Was this answer useful?  Yes


  • Jul 14th, 2015

Using @Id annotation with the field or its getter.
To attach generator user, @GeneratedValue

  Was this answer useful?  Yes


  • Jun 6th, 2017

We can define primary key using @id annotation
@id @GeneratedValue
Private int id;

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.


Related Answered Questions


Related Open Questions