Nick Div
Nick Div

Reputation: 5628

Is there a way I can insert the primary key myself instead of auto-generation in hibernate

<hibernate-mapping>
   <class name="Employee" table="EMPLOYEE">
      <meta attribute="class-description">
         This class contains the employee detail. 
      </meta>
      <id name="id" type="int" column="id">
         <generator class="native"/>
      </id>
      <property name="firstName" column="first_name" type="string"/>
      <property name="lastName" column="last_name" type="string"/>
      <property name="salary" column="salary" type="int"/>
   </class>
</hibernate-mapping>

As you can see in the above mapping file ID is automatically generated using generator class="native"

So is there a way that I can set this ID according to my logic from java. I dont want it to be automatically generated for me, I want to use my own logic to generate it and then insert in the table, and also is it possible that when I run the code to insert a value in the table then the table gets automatically created in the DB if it doesnt exist there already, I have heard that there is a way to do this.

Upvotes: 0

Views: 164

Answers (2)

ben75
ben75

Reputation: 28706

If you don't specify any generator for your primary key attribute, hibernate will assume you use the assign strategy. The assign strategy tells to hibernate that you will set id yourself, and so hibernate won't help you to define the id value. (hibernate will just throw an exception if you try to persist an entity with a null/already existing id)

So define your mapping like this:

<hibernate-mapping>
 <class name="Employee" table="EMPLOYEE">
  <meta attribute="class-description">
     This class contains the employee detail. 
  </meta>
  <id name="id" type="int" column="id"/>
  <property name="firstName" column="first_name" type="string"/>
  <property name="lastName" column="last_name" type="string"/>
  <property name="salary" column="salary" type="int"/>
 </class>
</hibernate-mapping>

Upvotes: 1

Luca Basso Ricci
Luca Basso Ricci

Reputation: 18403

Look at official doc from this point: all id generators are well explained.
Also you can check How to choose the id generation strategy when using JPA and Hibernate

Upvotes: 1

Related Questions