Oct 10, 2012

Hibernate tutorial with HSQLDB

This tutorial is basically an extension to the "simple" Java and JDBC tutorials. Hibernate is an ORM (Object to Relational Mapping) tool.

Step 1:  First step is to bring in the relevant Hibernate framework jar files like hibernate-xxx.jar, hibernate-annotations-xxxx.jar, and other dependent jar files that are transitively brought in from hibernate framework's pom.xml file. Here is the pom.xml file for simple Java project extended for hibernate.

<project xmlns="" xmlns:xsi=""





        <!-- jar that contains the HSQLDB driver class  -->

        <!--  GA means General Availability -->
        <!--  Hibernate framework JARS-->



Now, if you select the "simple" project and then right-mouse-click and select "Maven --> Update Dependencies".

Step 2: Hibernate uses the hibernate.cfg.xml file to configure the session factory with the database connectivity details and define your domain classes that map to to the relational database tables. This file needs to be defined in the src/main/resources folder and be in the classpath.

Create a new folder named "resources" under the "src/main" folder and then right-mouse-click on "resources" folder and then select "Build Path --> Use as Source Folder".

The contents of the hibernate.cfg.xml will include configuring the session factory to connect to the HSQLDB that we set up in the "SQL tutorial with HSQDB" tutorial.

<?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">org.hsqldb.jdbcDriver</property>
        <property name="connection.url">jdbc:hsqldb:hsql://localhost/mytestdb</property>
        <property name="connection.username">sa</property>
        <property name="connection.password"></property>
        <!-- JDBC connection pool (use the built-in) -->
        <property name="connection.pool_size">1</property>
        <!-- SQL dialect -->
        <property name="dialect">org.hibernate.dialect.HSQLDialect</property>
        <!-- Enable Hibernate's automatic session context management -->
        <property name="current_session_context_class">thread</property>
        <!-- Disable the second-level cache  -->
        <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
        <!-- Echo all executed SQL to stdout useful for debugging if set to true-->
        <property name="show_sql">false</property>
        <property name="">validate</property>
        <mapping class="com.mytutorial.domain.Course"/>

Step 3: The next step is to define the HibernateUtil class that bootstraps the hibernate by loading the SessionFactory via  the hibernate.cfg.xml.

import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;

public class HibernateUtil {
 private static final SessionFactory sessionFactory = buildSessionFactory();
    private static SessionFactory buildSessionFactory() {
        try {
            // Create the SessionFactory from hibernate.cfg.xml file
         return new AnnotationConfiguration().configure().buildSessionFactory();
        } catch (Throwable ex) {
            throw new ExceptionInInitializerError(ex);
    public static SessionFactory getSessionFactory() {
        return sessionFactory;


Step 4: Next step is to define the domain Course class that maps to the "Course" database  table that was created in the "SQL  with HSQLDB" tutorial. Annotations are used for the object to relational mapping

package com.mytutorial.domain;

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

public class Course {
 private Integer id;
 private String name;
 private String course;
 public Course() {}

 public Integer getId() {
  return id;

 public void setId(Integer id) { = id;

 public String getName() {
  return name;

 public void setName(String name) { = name;

 public String getCourse() {
  return course;

 public void setCourse(String course) {
  this.course = course;

Step 5: Define the data access layer interface and the implementation class. The CourseDao is the interface and CourseDaoImpl is the implementation class that retrieves data from the database.

Define the interface.

package com.mytutorial.dao;

public interface CourseDao {
 abstract void readAllCourses();


Define the implementation class.

package com.mytutorial.dao;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

import com.mytutorial.HibernateUtil;
import com.mytutorial.domain.Course;

public class CourseDaoImpl implements CourseDao {

 public void readAllCourses() {
  SessionFactory sf = HibernateUtil.getSessionFactory();
  Session session = sf.openSession();
  Query q = session.createQuery("from Course");
  List<Course> courses = q.list();
  for (Course course : courses) {
   System.out.println(course.getName() + " - " + course.getCourse());



Step 6: This step is to define a class with a main method that makes use of the CourseDao.

package com.mytutorial;

import com.mytutorial.dao.CourseDaoImpl;
import com.mytutorial.dao.CourseDao;

public class HibernateTutorial {
 public static void main(String[] args) {
  CourseDao cDao = new CourseDaoImpl();


You should now have the required Java files defined.

Step 7: Before you can run the, you need to make sure that the HSQL database is running with the Course database as demonstrated in the "SQL tutorial with HSQLDB".

c:\Tools\hsqldb-2.2.9\hsqldb>java -cp ./lib/hsqldb.jar org.hsqldb.server.Server
[Server@79616c7]: [Thread[main,5,main]]: checkRunning(false) entered
[Server@79616c7]: [Thread[main,5,main]]: checkRunning(false) exited
[Server@79616c7]: Startup sequence initiated from main() method
[Server@79616c7]: Loaded properties from [C:\Tools\hsqldb-2.2.9\hsqldb\]
[Server@79616c7]: Initiating startup sequence...
[Server@79616c7]: Server socket opened successfully in 198 ms.
[Server@79616c7]: Database [index=0, id=0, db=file:mydatabases/tutorialdb, alias=mytestdb] opened sucessfully in 1073 ms
[Server@79616c7]: Startup sequence completed in 1277 ms.
[Server@79616c7]: 2012-10-09 11:35:07.347 HSQLDB server 2.2.9 is online on port 9001
[Server@79616c7]: To close normally, connect and execute SHUTDOWN SQL
[Server@79616c7]: From command line, use [Ctrl]+[C] to abort abruptly

Step 8: The final step is to right-mouse-click on and then select "Run As --> Java Application".

You should get an output like:

Sam - Java
peter - J2EE
paul - JSF
jonathan - Hibernate
james - Spring
Lewis - JDBC

You should also see, hibernate logs as shown below

INFO: configuring from resource: /hibernate.cfg.xml
INFO: autocommit mode: false
09/10/2012 11:37:30 AM org.hibernate.connection.DriverManagerConnectionProvider configure
INFO: using driver: org.hsqldb.jdbcDriver at URL: jdbc:hsqldb:hsql://localhost/mytestdb
09/10/2012 11:37:30 AM org.hibernate.connection.DriverManagerConnectionProvider configure
INFO: connection properties: {user=sa, password=****}
INFO: Using dialect: org.hibernate.dialect.HSQLDialect
09/10/2012 11:37:31 AM org.hibernate.transaction.TransactionFactoryFactory buildTransactionFactory
INFO: Using default transaction strategy (direct JDBC transactions)
INFO: fetching database metadata
09/10/2012 11:37:31 AM org.hibernate.tool.hbm2ddl.TableMetadata <init>
09/10/2012 11:37:31 AM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: columns: [course, name, course_id]

In the Spring 3.0 tutorial, I will extend this tutorial to show how we can use Spring to inject CourseDao into HibernateTutorial.



Anonymous Anonymous said...

Does not work, maven update complains that hibernate does not exist

10:02 AM, October 20, 2012  
Blogger Arulkumaran Kumaraswamipillai said...

Pck a version that is available at the Maven 2 repository.

5:56 PM, October 20, 2012  
Blogger Arulkumaran Kumaraswamipillai said...

Try the repository for the relevant version number. In your settings.xml file you can configure additionalmrepositories.

6:08 PM, October 20, 2012  
Blogger Arulkumaran Kumaraswamipillai said...

Try 3.2.3.GA.

6:10 PM, October 20, 2012  
Anonymous arf said...

Thanks for your posting.It was very easy to understand.
Can you post some material that throws some light on drawback of hibernate as compared to JPA. Also how can we achieve loose coupling without using spring.
Thanks in advance

12:06 AM, September 30, 2013  
Anonymous beginner said...

great for helping people learn hibernate quickly. love tutorials with snippets code

10:39 AM, February 07, 2014  

Post a Comment

Subscribe to Post Comments [Atom]

Links to this post:

Create a Link

<< Home