First Hibernate Project

Before we begin you will need to download Hibernate and any other necessary JDBC jar files.   These will be used in your development environment inside of your Hibernate application.   We will work with MySQL and Microsoft SQL Server while exploring Hibernate so we must make sure the database or your choice has already been installed and set up.   For more details on that check our our tutorials on MySQL and SQL Server.

1. Download Hibernate

required_files

2. Hibernate Required Files

The following list of files will be required during our examples.   To make thing easier for us, I would recommend you create a user library in Eclipse and copy this set of eight (8) files.   These files can be found in the lib folders under librequired, libjpa and libbytecodejavassist.  Also, ensure that you pull in hibernate3.jar file that resides in the main folder under hibernate-distribution-3.6.4.Final.

  • hibernate3.jar
  • antlr-2.7.6.jar
  • commons-collections-3.1.jar
  • dom4j-1.6.1.jar
  • javassist-3.12.0.GA.jar
  • jta-1.1.jar
  • slf4j-api-1.6.1.jar
  • hibernate-jpa-2.0-api-1.0.0.Final.jar

3. Bring up Eclipse Environment

Once Eclipse is up, navigate over to the Package Explorer window and choose New Java Project — give it the name “FirstHibernateProject”.  Next we will create our Hibernate Add Library->User Library and add all the files detailed above.

user_libraryNext add the JDBC driver for the database you are planning on using.   For this example, I am using SQL Server so I downloaded the sqljdbc4.jar file.

4. Create the Hibernate Configuration File

Now its time to create the configuration file (hibernate.cfg.xml) and place it in the root of your application’s classpath.  I created a database called tutorial, and added a user called webuser that will access this database.

This XML configuration file needs to conform to the Hibernate 3 Configuration DTD.  As you can see from the file below, it is available from http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd.

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
    <session-factory>
        <!-- Database connection settings -->
        <property name="connection.driver_class">com.microsoft.sqlserver.jdbc.SQLServerDriver</property>
        <property name="connection.url">jdbc:sqlserver://localhost:1433;databaseName=tutorial</property>
        <property name="connection.username">webuser</property>
        <property name="connection.password">webuser123</property>

        <!-- JDBC connection pool (use the built-in) -->
        <property name="connection.pool_size">1</property>

        <!-- SQL dialect -->
        <property name="dialect">org.hibernate.dialect.SQLServer2008Dialect</property>

        <!-- Disable the second-level cache  -->
        <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>

        <!-- Echo all executed SQL to stdout -->
        <property name="show_sql">true</property>

        <!-- Drop and re-create the database schema on start up (create/update) -->
        <property name="hbm2ddl.auto">update</property>

        <property name="current_session_context_class">thread</property>

        <!-- Names the annotated entity class -->
        <mapping class="com.omega.dto.EmployeeDetails"/>

    </session-factory>
</hibernate-configuration>

5.  Hibernate Supports the following Databases

If you looked closely above, you might have noticed the following code snipet.

<property name=”dialect”>org.hibernate.dialect.SQLServer2008Dialect</property>

Hibernate supports many databases and although these are all supporting SQL via JDBC/JPA, there are still some slight variations in how each one implements their flavor of SQL.  Hence, hibernate needed to support many dialects, here are some:

DatabaseHibernate Dialect
DB2org.hibernate.dialect.DB2Dialect
Derbyorg.hibernate.dialect.DerbyDialect
Firebirdorg.hibernate.dialect.FirebirdDialect
FrontBaseorg.hibernate.dialect.FrontBaseDialect
H2org.hibernate.dialect.H2Dialect
HSQLorg.hibernate.dialect.HSQLDialect
Informixorg.hibernate.dialect.InformixDialect
Ingresorg.hibernate.dialect.IngresDialect
Interbaseorg.hibernate.dialect.InterbaseDialect
JDataStoreorg.hibernate.dialect.JDataStoreDialect
McKoiorg.hibernate.dialect.McKoiDialect
Mimerorg.hibernate.dialect.MimerDialect
MySQLorg.hibernate.dialect.MySQLDialect
Oracleorg.hibernate.dialect.OracleDialect
Pointbaseorg.hibernate.dialect.PointbaseDialect
Postgresorg.hibernate.dialect.PostgresDialect
SAP DBorg.hibernate.dialect.SAPDBDialect
SQL Serverorg.hibernate.dialect.SQLServerDialect
Sybaseorg.hibernate.dialect.SybaseDialect
Teradataorg.hibernate.dialect.TeradataDialect
Timetenorg.hibernate.dialect.TimestenDialect

6. Database Creation

For this tutorial, we will create the table ’employee’ in SQL Server. You can use the following script to aid you in it’s creation.

USE tutorial
go

IF OBJECT_ID('dbo.employee') IS NOT NULL
BEGIN
  DROP TABLE dbo.employee
  IF OBJECT_ID('dbo.employee') IS NOT NULL
    PRINT '<<< FAILED DROPPING TABLE dbo.employee >>>'
  ELSE
    PRINT '<<< DROPPED TABLE dbo.employee >>>'
  END
go

CREATE TABLE dbo.employee (
  employee_id int             NOT NULL,
  first_name  varchar(30)     NOT NULL,
  last_name   varchar(50)     NOT NULL,
  pay_type    char(2)         NULL,
  pay_rate    numeric(18, 2)  NULL,
  start_date  date            NULL,
  end_date    date            NULL
)
go

ALTER TABLE dbo.employee
    ADD CONSTRAINT employee_pk
    PRIMARY KEY CLUSTERED (employee_id)
go

7. Our Java source code

Now we can begin to write our Java source files. Below you will find the employee.java entity class which has some annotations from the JPA or Java Persistence API.

  • @Entity — This specifies that this class is an Entity
  • @Table — This annotation specifies the table name for this entity.  It allows you to override and specify what table specifically you would like to use for this entity.  Otherwise, hibernate would create/update a table called EmployeeDetails
  • @Column — It specifies the details of the column to be mapped.  These will include name, length, nullable and unique properties.
  • @Id — This annotation specifies the primary key of the entity

 

package com.omega.dto;

import java.util.Date;

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

@Entity
@Table(name="dbo.employee")
public class EmployeeDetails {
	@Id
	@Column(name="employee_id")
	private int employeeID;

	@Column(name="first_name")
	private String firstName;

	@Column(name="last_name")
	private String lastName;

	@Column(name="pay_type")
	private String payType;

	@Column(name="pay_rate")
	private double payRate;

	@Column(name="start_date")
	private Date startDate;

	@Column(name="end_date")
	private Date endDate;

	public int getEmployeeID() {
		return employeeID;
	}

	public void setEmployeeID(int employeeID) {
		this.employeeID = employeeID;
	}

	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 getPayType() {
		return payType;
	}

	public void setPayType(String payType) {
		this.payType = payType;
	}

	public double getPayRate() {
		return payRate;
	}

	public void setPayRate(double payRate) {
		this.payRate = payRate;
	}

	public Date getStartDate() {
		return startDate;
	}

	public void setStartDate(Date startDate) {
		this.startDate = startDate;
	}

	public Date getEndDate() {
		return endDate;
	}

	public void setEndDate(Date endDate) {
		this.endDate = endDate;
	}
}

8. Creating a Static Hibernate class

This utility class will instantiate SessionFactory in hibernate. It will be called several times from the HibernateTest.java program.

package com.omega.utility;

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

public class Hibernate {
    private static final SessionFactory sessionFactory = createSessionFactory();

    private static SessionFactory createSessionFactory() {
      try {
        System.out.println("Initial SessionFactory creation...");
        return new Configuration().configure().buildSessionFactory();
      } catch (Throwable ex) {
      System.err.println("Initial SessionFactory creation has failed with exception: " + ex);
      throw new ExceptionInInitializerError(ex);
    }
  }

  public static SessionFactory getSessionFactory() {
    return sessionFactory;
  }
}

9. Creating the main class

Using the main class we can now begin our initial test to see if we can insert new records into the database.

package com.omega;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

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

import com.omega.dto.EmployeeDetails;
import com.omega.utility.Hibernate;

public class HibernateTest {

  public static void main(String[] args) throws ParseException {

    SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
    Date startDate = null;

    EmployeeDetails employee = new EmployeeDetails();
    employee.setEmployeeID(100);
    employee.setFirstName("Babe");
    employee.setLastName("Ruth");
    employee.setPayType("S");
    employee.setPayRate(125700);
    startDate = sdf.parse("02/14/2013");
    employee.setStartDate(startDate);

    SessionFactory factory = Hibernate.getSessionFactory();
    Session session = factory.openSession();
    session.beginTransaction();
    session.save(employee);
    session.getTransaction().commit();

    EmployeeDetails employee1 = new EmployeeDetails();
    employee1.setEmployeeID(101);
    employee1.setFirstName("Derek");
    employee1.setLastName("Jeter");
    employee1.setPayType("S");
    employee1.setPayRate(53500);
    startDate = sdf.parse("04/08/2006");
    employee1.setStartDate(startDate);

    SessionFactory factory1 = Hibernate.getSessionFactory();
    Session session1 = factory.openSession();
    session1.beginTransaction();
    session1.save(employee1);
    session1.getTransaction().commit();
  }
}

10. Verifying Changes in Microsoft SQL Server

I am connecting to Microsoft SQL Server using DBeaver from JKiss. This Universal DB tool can be found at: http://dbeaver.jkiss.org/.   Prior to running the application, the database had nine (9) records.  After we executed the HibernateTest application,  you can see the new records with employee_ids of 100 and 101 respectively.

first_hibernate_save_into_db3

 11. That’s It

Next we will show you how to implement CRUD operations using Hibernate.  In addition, we will show you how to map using XML files as opposed to using annotations.

 

 

Please Share Us on Social Media

Facebooktwittergoogle_plusredditpinterestlinkedinmail

Leave a Reply

Your email address will not be published. Required fields are marked *