Sample Hibernate Application

The objective of this example is to create event objects and store these events in a database and retrieve them for display using Hibernate. You may want to look at Hibernate Installation/Setup on Eclipse IDE article if Hibernate is not installed already on your system.

There are two approach to develop hibernate applications. The first one is “Using hibernate XML mapping files” and the other one is “Using JPA or Hibernate annotations”.

Using Hibernate XML Mapping Files

org.hibernate.tutorial.domain package
Create a new Java package in the src directory(source directory of your project) and enter org.hibernate.tutorial.domain as the package name.

The first class
Create a new Java class(Event.java) in the org.hibernate.tutorial.domain package.
Event class represents the event we want to store in the database; it is a simple JavaBean class with some properties:
Event.java : A simple persistent class

package org.hibernate.tutorial.domain;

import java.util.Date;

public class Event {
    private Long id;

    private String title;
    private Date date;

    public Event() {}

    public Long getId() {
        return id;
    }

    private void setId(Long id) {
        this.id = id;
    }

    public Date getDate() {
        return date;
    }

    public void setDate(Date date) {
        this.date = date;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }
}

The mapping file
Create a new XML file(Event.hbm.xml) which is our mapping file in the org.hibernate.tutorial.domain package.
Hibernate needs to know how to load and store objects of the persistent class. This is where the Hibernate mapping file comes into play. The mapping file tells Hibernate what table in the database it has to access, and what columns in that table it should use.
Event.hbm.xml : A simple hibernate XML mapping

<?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 package="org.hibernate.tutorial.domain">

    <class name="Event" table="EVENTS">
        <id name="id" column="EVENT_ID">
            <generator class="increment"/>
        </id>
        <property name="date" type="timestamp" column="EVENT_DATE"/>
        <property name="title" column="EVENT_TITLE"/>
    </class>

</hibernate-mapping>

Hibernate configuration
At this point, you should have the persistent class and its mapping file in place. It is now time to configure Hibernate.
Create a new XML file and give this new configuration file the default name hibernate.cfg.xml and place it directly in the source directory(src directory) of your project, outside of any package.

hibernate.cfg.xml : A simple Hibernate XML configuration file

<?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">oracle.jdbc.driver.OracleDriver</property>
        <property name="connection.url">jdbc:oracle:thin:@127.0.0.1:1521:xe</property>
        <property name="connection.username">username</property>
        <property name="connection.password">password</property>

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

        <!-- JDBC connection pool (use the built-in) -->
        <property name="connection.pool_size">1</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 -->
        <property name="show_sql">true</property>

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

        <mapping resource="org/hibernate/tutorial/domain/Event.hbm.xml"/>

    </session-factory>

</hibernate-configuration>

Note: If you want to log in to Oracle Database XE as the Administrator you must enter system for the user name and enter the password that was specified when Oracle Database XE was installed.

Note: The configuration above is for the Oracle XE database. If you use an another database management system already installed, you should change some properties in this configuration file. For example, if your database is MySQL, you must replace some properties like this :

...
        <!-- Database connection settings -->
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost/SampleDB</property>
        <property name="connection.username">root</property>
        <property name="connection.password"></property>

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

org.hibernate.tutorial.util package
Create a new Java package in the src directory(source directory of your project) and enter org.hibernate.tutorial.util as the package name.

Startup and helpers
It is time to load and store some Event objects, but first you have to complete the setup with some infrastructure code. You have to startup Hibernate by building a global org.hibernate.SessionFactory object and storing it somewhere for easy access in application code. A org.hibernate.SessionFactory is used to obtain org.hibernate.Session instances. A org.hibernate.Session represents a single-threaded unit of work. The org.hibernate.SessionFactory is a thread-safe global object that is instantiated once.

Create a new Java class(HibernateUtil.java) in the org.hibernate.tutorial.util package that takes care of startup and makes accessing the org.hibernate.SessionFactory more convenient.

HibernateUtil.java : The HibernateUtil class for startup and SessionFactory handling

package org.hibernate.tutorial.util;

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

public class HibernateUtil {

    private static final SessionFactory sessionFactory = buildSessionFactory();

    private static SessionFactory buildSessionFactory() {
        try {
            // Create the SessionFactory from hibernate.cfg.xml
            return new Configuration().configure().buildSessionFactory();
        }
        catch (Throwable ex) {
            // Make sure you log the exception, as it might be swallowed
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }

}

org.hibernate.tutorial package
Create a new Java package in the src directory(source directory of your project) and enter org.hibernate.tutorial as the package name.

Loading and storing objects
We are now ready to start doing some real work with Hibernate.
Create a new Java class(EventManager.java) with a main() method in the org.hibernate.tutorial package.
EventManager.java : The “HibernateApplication” main application code

package org.hibernate.tutorial;

import org.hibernate.Session;

import java.util.*;

import org.hibernate.tutorial.domain.Event;
import org.hibernate.tutorial.util.HibernateUtil;

public class EventManager {

    public static void main(String[] args) {
        EventManager mgr = new EventManager();

        mgr.createAndStoreEvent("My First Event", new Date());

        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.YEAR, 2012); // Year
        calendar.set(Calendar.MONTH, 0);   // Month, The first month of the year is JANUARY which is 0
        calendar.set(Calendar.DATE, 1);    // Day, The first day of the month has value 1.
        mgr.createAndStoreEvent("My Second Event", calendar.getTime());

        List events = mgr.listEvents();
        for (int i = 0; i < events.size(); i++) {
            Event theEvent = (Event) events.get(i);
            System.out.println(
                    "Event: " + theEvent.getTitle() + " Time: " + theEvent.getDate()
            );
        }

        HibernateUtil.getSessionFactory().close();
    }

    private void createAndStoreEvent(String title, Date theDate) {
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        session.beginTransaction();

        Event theEvent = new Event();
        theEvent.setTitle(title);
        theEvent.setDate(theDate);
        session.save(theEvent);

        session.getTransaction().commit();
    }

    private List listEvents() {
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        session.beginTransaction();
        List result = session.createQuery("from Event").list();
        session.getTransaction().commit();
        return result;
    }

}

The final appearance of the application should be as follows:
LastappearanceOfApp

Now our project is ready. Right click to project or right click to EventManager.java and click Run As–>Java Application.

Events
You will see the events stored in “EVENTS” table in the database if there is not a problem.

Note: If you get a message when you run your application like:
Disabling contextual LOB creation as createClob() method threw error : java.lang.reflect.InvocationTargetException
You can add

<property name="hibernate.temp.use_jdbc_metadata_defaults">false</property>

line to the hibernate.cfg.xml file to solve this problem.
For more detailed explanation:
http://stackoverflow.com/questions/4588755/hibernate-disabling-contextual-lob-creation-as-createclob-method-threw-error

Using Annotations
We will use JPA Annotations to replace the Hibernate XML mapping files with inline metadata.

You may want to copy your existing “HibernateApplication” project directory before you make the following changes—you’ll migrate from native Hibernate to standard JPA mappings.

Now delete the src/org.hibernate.tutorial.domain/Event.hbm.xml file. You’ll replace this file with annotations in the src/org.hibernate.tutorial.domain/Event.java class source.

Event.java: Mapping the Event class with Annotations

package org.hibernate.tutorial.domain;

import java.util.Date;

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

@Entity
@Table(name="EVENTS")
public class Event {
    @Id
    @GeneratedValue
    @Column(name="EVENT_ID")
    private Long id;

    @Column(name="EVENT_TITLE")
    private String title;

    @Temporal(TemporalType.TIMESTAMP)
    @Column(name="EVENT_DATE")
    private Date date;

    public Event() {}

    public Long getId() {
        return id;
    }

    private void setId(Long id) {
        this.id = id;
    }

    public Date getDate() {
        return date;
    }

    public void setDate(Date date) {
        this.date = date;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }
}

The other change you need to make to your project, besides deleting the now obsolete XML mapping file, is a change in the Hibernate configuration, in hibernate.cfg.xml.
Replace

<mapping resource="org/hibernate/tutorial/domain/Event.hbm.xml"/>

line with

<mapping class="org.hibernate.tutorial.domain.Event"/>

Finally, you should replace

return new Configuration().configure().buildSessionFactory();

line in HibernateUtil.java with

Configuration cfg = new Configuration();
cfg.addAnnotatedClass(org.hibernate.tutorial.domain.Event.class);
return cfg.configure().buildSessionFactory();

This is all you need to change to run the example application with annotations.Try running it again. You should see the events stored in the “EVENTS” table in your database.

Advertisements

About kaanmutlu

Software Developer - Computer Engineer from Istanbul, Turkey
This entry was posted in Uncategorized and tagged , . Bookmark the permalink.

9 Responses to Sample Hibernate Application

  1. Rocky says:

    A prefect way to get started on Hibernate for a person who is completely a beginner.
    You rock….best and good example with step by step details to execute the code in Eclipse..

  2. Thanks for this how to ! It’s really helping us !
    Thanks a lot !

  3. Tuyen says:

    Does we should create table EVENTS in database first?

  4. xiaofeng says:

    I try to replicate your tutorial with hibernate 4.38 final, using mysql 5.5 server.

    I got the following error in my console, your kind reply is highly appreciated!

    ERROR: HHH000319: Could not get database metadata
    com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table ‘test.user_sequences’ doesn’t exist
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:377)
    at com.mysql.jdbc.Util.getInstance(Util.java:360)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:978)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3887)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3823)
    at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2435)
    at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2582)
    at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2526)
    at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2484)
    at com.mysql.jdbc.StatementImpl.executeQuery(StatementImpl.java:1446)
    at org.hibernate.tool.hbm2ddl.DatabaseMetadata.initSequences(DatabaseMetadata.java:178)
    at org.hibernate.tool.hbm2ddl.DatabaseMetadata.(DatabaseMetadata.java:92)
    at org.hibernate.tool.hbm2ddl.DatabaseMetadata.(DatabaseMetadata.java:84)
    at org.hibernate.tool.hbm2ddl.SchemaUpdate.execute(SchemaUpdate.java:221)
    at org.hibernate.tool.hbm2ddl.SchemaUpdate.execute(SchemaUpdate.java:203)
    at org.hibernate.internal.SessionFactoryImpl.(SessionFactoryImpl.java:522)
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1859)
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1930)
    at org.hibernate.tutorial.util.HibernateUtil.buildSessionFactory(HibernateUtil.java:13)
    at org.hibernate.tutorial.util.HibernateUtil.(HibernateUtil.java:8)
    at org.hibernate.tutorial.EventManager.createAndStoreEvent(EventManager.java:35)
    at org.hibernate.tutorial.EventManager.main(EventManager.java:15)

    Feb 03, 2015 4:57:34 PM org.hibernate.tool.hbm2ddl.SchemaUpdate execute
    ERROR: HHH000299: Could not complete schema update
    com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table ‘test.user_sequences’ doesn’t exist
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:377)
    at com.mysql.jdbc.Util.getInstance(Util.java:360)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:978)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3887)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3823)
    at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2435)
    at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2582)
    at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2526)
    at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2484)
    at com.mysql.jdbc.StatementImpl.executeQuery(StatementImpl.java:1446)
    at org.hibernate.tool.hbm2ddl.DatabaseMetadata.initSequences(DatabaseMetadata.java:178)
    at org.hibernate.tool.hbm2ddl.DatabaseMetadata.(DatabaseMetadata.java:92)
    at org.hibernate.tool.hbm2ddl.DatabaseMetadata.(DatabaseMetadata.java:84)
    at org.hibernate.tool.hbm2ddl.SchemaUpdate.execute(SchemaUpdate.java:221)
    at org.hibernate.tool.hbm2ddl.SchemaUpdate.execute(SchemaUpdate.java:203)
    at org.hibernate.internal.SessionFactoryImpl.(SessionFactoryImpl.java:522)
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1859)
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1930)
    at org.hibernate.tutorial.util.HibernateUtil.buildSessionFactory(HibernateUtil.java:13)
    at org.hibernate.tutorial.util.HibernateUtil.(HibernateUtil.java:8)
    at org.hibernate.tutorial.EventManager.createAndStoreEvent(EventManager.java:35)
    at org.hibernate.tutorial.EventManager.main(EventManager.java:15)

    • xiaofeng says:

      Kaan, thanks for the great examples. I got it fixed. The problem is that I have an extra line like this in my xml file.


      <!–org.hibernate.dialect.OracleDialect –>

      so now it is working fine. Thanks!

  5. Amit says:

    Getting “The filename, direcory name, or volume label syntax is incorrect.” error

  6. Asik Ali Sahul Hameed says:

    I tried the above mentioned steps. But I got this Errors. Please some on tell me how can i solved this:
    SLF4J: The requested version 1.6 by your slf4j binding is not compatible with [1.5.5, 1.5.6, 1.5.7, 1.5.8]
    SLF4J: See http://www.slf4j.org/codes.html#version_mismatch for further details.
    351 [main] INFO org.hibernate.cfg.Environment – Hibernate 3.5.6-Final
    354 [main] INFO org.hibernate.cfg.Environment – hibernate.properties not found
    361 [main] INFO org.hibernate.cfg.Environment – Bytecode provider name : javassist
    379 [main] INFO org.hibernate.cfg.Environment – using JDK 1.4 java.sql.Timestamp handling
    674 [main] INFO org.hibernate.cfg.Configuration – configuring from resource: hibernate.cfg.xml
    674 [main] INFO org.hibernate.cfg.Configuration – Configuration resource: hibernate.cfg.xml
    Initial SessionFactory creation failed.org.hibernate.HibernateException: hibernate.cfg.xml not found
    Exception in thread “main” java.lang.ExceptionInInitializerError
    at org.hibernate.tutorial.util.HibernateUtil.buildSessionFactory(HibernateUtil.java:21)
    at org.hibernate.tutorial.util.HibernateUtil.(HibernateUtil.java:8)
    at org.hibernate.tutorial.EventManager.createAndStoreEvent(EventManager.java:36)
    at org.hibernate.tutorial.EventManager.main(EventManager.java:16)
    Caused by: org.hibernate.HibernateException: hibernate.cfg.xml not found
    at org.hibernate.util.ConfigHelper.getResourceAsStream(ConfigHelper.java:170)
    at org.hibernate.cfg.Configuration.getConfigurationInputStream(Configuration.java:1497)
    at org.hibernate.cfg.Configuration.configure(Configuration.java:1519)
    at org.hibernate.tutorial.util.HibernateUtil.buildSessionFactory(HibernateUtil.java:14)

  7. Keith Williams says:

    This was extremely helpful. You made Hibernate simple. Thank you very much.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s