Skip to main content

Hibernate auto increment with example

In previous example we learn how to map java object with database table for manually(not using auto increment) assigned all the values. To create primary key auto increment application by using hibernate mapping(hbm.xml) or using annotations continue reading this article. 

We need to create a database and create an employee table by using the below query.

Table:
CREATE table EMPLOYEE(
eid integer(10) primary key not null,
firstname varchar(30),
lastname varchar(30),
designation varchar(30),
salary double(10,2));

Here, we will create a bean/POJO (Plain Old Java Object) class of employee.

Employee.java:
package com.javatbrains.hibernate;

import java.io.Serializable;

/*This is the POJO class. It contains only Getter and Setter methods*/
public class Employee implements Serializable {
     private static final long serialVersionUID = -75885815725314443L;
    
     private int eid;
     private String firstName;
     private String lastName;
     private String designation;
     private double salary;

     public int getEid() {
          return eid;
     }

     public void setEid(int eid) {
          this.eid = eid;
     }

     public String getFirstName() {
          return firstName;
     }

     public void setFirstName(String firstName) {
          this.firstName = firstName;
     }

     public String getLastName() {
          return lastName;
     }

     public void setLastName(String lastName) {
          this.lastName = lastName;
     }

     public String getDesignation() {
          return designation;
     }

     public void setDesignation(String designation) {
          this.designation = designation;
     }

     public double getSalary() {
          return salary;
     }

     public void setSalary(double salary) {
          this.salary = salary;
     }

}

          In Employee.java class contains eid, firstName, lastName, designation, salary of employee and setters and getter's of those properties. Here, emp is the auto increment, you no need to set the value explicitly.

employee.hbm.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
     <class name="com.ora.hibernate.examples.Employee" table="EMPLOYEE">
          <id name="eid" type="int">
              <column name="EID" />
              <generator class="increment" />
          </id>
          <property name="firstName" type="java.lang.String">
              <column name="FIRSTNAME" />
          </property>
          <property name="lastName" type="java.lang.String">
              <column name="LASTNAME" />
          </property>
          <property name="designation" type="java.lang.String">
              <column name="DESIGNATION" />
          </property>
          <property name="salary" type="double">
              <column name="SALARY" />
          </property>
     </class>
</hibernate-mapping>

          The above Employee java class mapping into database table ‘EMPLOYEE’ by using <class> tag in hibernate mapping file. In that file class properties are mapping into database table columns by using <property> and <class> tags. Here, <class> tag is not necessary, it is an optional tag.

Note: if you can’t specify the <column> tag, java class property name automatically taken by database table column name.
Now, I am trying to create hibernate configuration file.

hibernate.cfg.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
     <session-factory>
          <property name="hibernate.connection.driver_class"> com.mysql.jdbc.Driver </property>
          <property name="hibernate.connection.url"> jdbc:mysql://localhost:3306/hibernatex </property>
          <property name="hibernate.connection.username"> root </property>
          <property name="hibernate.connection.password"> root </property>
          <property name="hibernate.dialect"> org.hibernate.dialect.MySQLDialect </property>
          <mapping resource="com/ora/hibernate/examples/Employee.hbm.xml"
              package="com.ora.hibernate.examples" />
     </session-factory>
</hibernate-configuration>

          In the above configuration file contains the database properties of driver, connection url, user name, password, dialect. Here, dialect is the vendor specific one, there I am using MySQL Dialect. If your using any other databases like, Oracle, postgreSQL. You must specify that particular dialect.

          Finally, there I am mapping the employee.hbm.xml file into hibernate.cfg.xml file by using the <mapping> tag.

EmployeeTest.java:
package com.javatbrains.hibernate;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

public class EmployeeTest {

     public static void main(String[] args) {
          Employee emp = new Employee();
          emp.setFirstName("Subbareddy");
          emp.setLastName("Nallamachu");
          emp.setDesignation("Software Engineer");
          emp.setSalary(12000.00d);

          SessionFactory sessionFactory = new Configuration().configure()
                   .buildSessionFactory();
          Session session = sessionFactory.openSession();
          Transaction transaction = session.beginTransaction();
          session.save(emp);
          transaction.commit();
          session.close();
     }

}

·         In the above EmployeeTestclass, I am trying to insert Employee java class object values into database 'EMPLOYEE' table. Here, you can see below steps to understand 'EmployeeTest' class.
·         Create 'Employee' object and set those values.
·         Create SessionFactory instance by using configure() method in Configuration class.
·         Open a session instance by using the openSession() providing by SessionFactory interface.
·         Get Transaction instance by using beginTransaction() method providing by Session interface.
·         Use save (Object obj), saveOrUpdate (Object obj) to save Employee object values into database table.
·         Then commit transaction by using commit () method providing by Transaction interface.
·         Finally, close session by using close() method providing by Session interface.

Same example with Hibernate Annotations:

          Now, I am explains how to do the same example by using hibernate annotations. This is simple and easy for programmers to do application with annotations. By using hibernate annotations we are not required to create any of hibernate mapping files in an application. Before going to do changes on old application you must read few annotations and their uses.

@Entity: declares the class as an entity bean.

@Table: is set at the class level. It allows you to define the table, catalogue and schema names for your entity mapping. If @Table is not defined the default values are used. The unqualified class of the entity.

@ID: declares the identifier property of this entity bean. This represents the primary key column in the table.

@Column: declares column level (properties of the persistence class). This is the optional annotation. This annotation represents the database table column.

@GeneratedValue: is set at the identifier property level. That defined the generatedValue type as AUTO_IDENTITY, SEQUENCE, TABLE. If you declared generatedValue type as AUTO, you no need to enter the value manually for that field. That represents the AUTO_INCREMENT at database table level.

Now coming to the application, majorly you need to do few changes in old application to convert hbm application to annotation application. In that mainly you need to change persistence (Employee.java) class. In this situation Employee.hbm.xml file is not required. You can change your old Employee.java file as like below,

Employee.java:
package com.javatbrains.hibernate;

import java.io.Serializable;

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

import org.hibernate.annotations.Entity;

@Entity
@Table(name = "EMPLOYEE", catalog = "hibernatex")
public class Employee implements Serializable {
     private static final long serialVersionUID = -75885815725314443L;

     @Id
     @GeneratedValue
     @Column(name = "EID")
     private int eid;
     @Column(name = "FIRSTNAME")
     private String firstName;
     @Column(name = "LASTNAME")
     private String lastName;
     @Column(name = "DESIGNATION")
     private String designation;
     @Column(name = "SALARY")
     private double salary;

     public int getEid() {
          return eid;
     }

     public void setEid(int eid) {
          this.eid = eid;
     }

     public String getFirstName() {
          return firstName;
     }

     public void setFirstName(String firstName) {
          this.firstName = firstName;
     }

     public String getLastName() {
          return lastName;
     }

     public void setLastName(String lastName) {
          this.lastName = lastName;
     }

     public String getDesignation() {
          return designation;
     }

     public void setDesignation(String designation) {
          this.designation = designation;
     }

     public double getSalary() {
          return salary;
     }

     public void setSalary(double salary) {
          this.salary = salary;
     }

}

          Once you done by editing the persistence class, Open hibernate.cfg.xml file and remove/comment the old mapping tag. Because your mapping Employee.hbm.xml, but now that is not required. We need to map Employee.java class into mapping file by using mapping tag. As like below,

<mapping class="com.javatbrains.hibernate.Employee"/>

          Once completed to do mapping of persistence class. Then go into EmployeeTest.java class and build Session Factory by using “Annotation Configuration” class. As like below line,

SessionFactory sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();

          You have done all the changes, just run it EmployeeTest.java class. You did’t get any exceptions your class executing successfully and your values inserted successfully into database. Open database and check employee table values are inserted are not.

Comments

Popular posts from this blog

Multithreading in java with example

Multithreading  is one of the most important concept in core java. In this article we will learn what is multithreading? , what is the use of it? and What is the use of Synchronization and when to use it?  with detailed examples. At a time, two or more threads are accessing the same object is called as Multithreading  in Java .  First, we will create two threads for two objects. It is also possible to run two or more threads on a single class object. In this case, there is a possibility to get unreliable results. If the two threads are perform same task, then they need same object to be executed each time. For your better understanding, take an example of any reservations like, railway, movie ticket booking,etc. Let us think only one berth is available in a train and two passengers are asking for that berth. The first person has sent a request to allocate that ticket/berth to him. At the same time, the second person also sent a request to allocate that ...

Git installation for AngularJS 2 in Windows 10

Download Git latest version from https://git-scm.com/downloads or you click on the below link to download directly for windows https://git-scm.com/download/win . Once download completes, click on executable file to start installation process and choose Yes to allow the software installation in windows 10. Click on Next button to continue further installation. Browse the isntallation directory and click on Next button to continue. Select the list of components which you want to be installed and click on Next button to proced further installation. Type the shortcut name for Start menu and click on Next button. Select how you want to use the Git and click on Next button. For Windows no need to change anything, let it be the default one. Choose the Use the OpenSSL library and click on Next button. Select how should Git treat line ending in text files and click on Next button. Select which terminal emulator to use with Git and click on Next button. Configure extr...

JNDI configuration for Tomcat 9 with Oracle

In this article, I am going to place the required source code to get data from the table by using the JNDI configuration. Below are the environment details that I have configured currently. Windows - 7 Oracle - 10g Tomcat - 9 JDK - 8 Eclipse Oxygen Ojdbc6 jar required First, we need to create the Dynamic Web Project. If you don't know how to do <Click Here>. I have faced a lot of issues before getting the output like 405, No driver class to load, etc. I am using JSP & Servlets in the current explanation. Before started writing the application logic, we need to do the below configuration in the installed tomcat directory. Place OJDBC6.jar in the Tomcat LIB directory. Add this Resource under <GlobalNamingResources> in Server.xml file which is present under the conf directory in Tomcat. < Resource name = "jdbc/myoracle" global= "jdbc/myoracle" auth = "Container" type= "javax.sql.DataSource" driverClass...