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


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

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

        <!-- Database connection settings -->
        <property name="connection.driver_class"></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="">update</property>

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

        <!-- Names the annotated entity class -->
        <mapping class=""/>


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
SAP DBorg.hibernate.dialect.SAPDBDialect
SQL Serverorg.hibernate.dialect.SQLServerDialect

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

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

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

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

7. Our Java source code

Now we can begin to write our Java source files. Below you will find the 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



import java.util.Date;

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

public class EmployeeDetails {
	private int employeeID;

	private String firstName;

	private String lastName;

	private String payType;

	private double payRate;

	private Date startDate;

	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 program.


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.


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;


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();
    startDate = sdf.parse("02/14/2013");

    SessionFactory factory = Hibernate.getSessionFactory();
    Session session = factory.openSession();

    EmployeeDetails employee1 = new EmployeeDetails();
    startDate = sdf.parse("04/08/2006");

    SessionFactory factory1 = Hibernate.getSessionFactory();
    Session session1 = factory.openSession();

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:   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.


 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


Leave a Reply

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