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

how to count the page views by using JSP

Multithreading in java with example

How to retrieve data from table by using JDBC with example

Prime, Fibonacci and Factorial number with example in java

How to insert images into database using JDBC?

How to sort list of objects in java with examples

String interview questions and answers

Exception in thread "main" java.lang.NoClassDefFoundError: javax/transaction/SystemException

Store file into table by using JDBC with example