Hibernate configuration file

This file contains the configuration information needed by Hibernate to connect to a RDBMS. For Hibernate's configuration, we can use a simple hibernate.properties file, a slightly more sophisticated hibernate.cfg.xml file, or even complete programmatic setup. Most users prefer the XML configuration file.

<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
    <session-factory>

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


        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost/hibernatetutorial</property>
        <property name="hibernate.connection.username">user</property>
        <property name="hibernate.connection.password">password</property>
        <property name="transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</property>

        <!-- Automatic schema creation (begin) === -->
        <property name="hibernate.hbm2ddl.auto">create</property>


        <!-- Simple memory-only cache -->
        <property name="hibernate.cache.provider_class">org.hibernate.cache.HashtableCacheProvider</property>

        <!-- Enable Hibernate's automatic session context management -->
        <property name="current_session_context_class">thread</property>

        <!-- ############################################ -->
        <!-- # mapping files with external dependencies # -->
        <!-- ############################################ -->

        <mapping resource="com/sample/model/Person.hbm.xml" />

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

As you can see, hibernate.cfg.xml configures the dialect, the JDBC parameters, the connection pool, the cache provider and the single classes mapped.
This example uses MySQL as database. You need to create a database named "hibernatetutorial" and assign to the user "hibernate" all the privileges required.

mysql> create database hibernatetutorial;
Query OK, 1 row affected (0.00 sec)

CREATE USER 'user'@'localhost' IDENTIFIED BY 'password';

mysql> use hibernatetutorial;
Database changed

mysql> grant all privileges on hibernatetutorial to user;
Query OK, 0 rows affected (0.03 sec)

In this configuration file we have set the property "hibernate.hbm2ddl.auto" to true which means automatic drop/creation of the database schema. Remember to comment this line after the first run. At the bottom we have declared the resource "com/sample/Person.hbm.xml" which is the mapping for Class Person.

The hibernate.cfg.xml file needs to be added to the Java classpath. You can include it into the src folder of your Project which is included by default in the classpath.

Coding a Test class

For completing our Hibernate tutorial we'll create a Java Class “TestPerson” in the package “com.sample”. Add the following source code. It includes methods to create entries in the database, to update and to list them.

package com.sample.test;

import java.util.List;
 
import org.hibernate.Query;
import org.hibernate.Session;

import com.sample.model.Person;
import com.sample.util.SessionFactoryUtil;
 
 
public class TestPerson {
 
    public static void main(String[] args) {
        Session session = SessionFactoryUtil.getSessionFactory().getCurrentSession();
 
        session.beginTransaction();
 
        createPerson(session);
 
        queryPerson(session);
 
    }
 
    private static void queryPerson(Session session) {
    	
    	
    	
        Query query = session.createQuery("from Person");                 
        List <Person>list = query.list();
        java.util.Iterator<Person> iter = list.iterator();
        while (iter.hasNext()) {
 
            Person person = iter.next();
            System.out.println("Person: \"" + person.getName() +"\", " + person.getSurname() +"\", " +person.getAddress());
 
        }
 
        session.getTransaction().commit();
 
    }
 
    public static void createPerson(Session session) {
        Person person = new Person();
 
        person.setName("Barak");
        person.setSurname("Obama");       
        person.setAddress("White House");       
 
        session.save(person);
    }
}

As you can see the TestPerson starts at first building a SessionFactory: this object is used to open up new Sessions. A Session represents a single-threaded unit of work, the SessionFactory is a thread-safe global object, instantiated once.

A Session is a single unit of work and begins when it is first needed, that is when the first call to getCurrentSession() is made. It is then bound by Hibernate to the current thread. When the transaction ends, either through commit or rollback, Hibernate automatically unbinds the Session from the thread and closes it for you.

In this example we use a SessionFactoryUtil class to instantiate the SessionFactory just once:

package com.sample.util;

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


public class SessionFactoryUtil {

    private static final SessionFactory sessionFactory;

    static {
        try {
            // Create the SessionFactory from hibernate.cfg.xml
            sessionFactory = 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;
    }

}

Ok, if you have completed all the steps your project should look like this:

project hibernate eclipse jboss wildfly

Run the main class in order to test it. A new row will be inserted, which is confirmed by logging into mysql client:

mysql> select * from PERSON;
+----+-------+---------+-------------+
| ID | NAME  | SURNAME | ADDRESS     |
+----+-------+---------+-------------+
|  1 | Barak | Obama   | White House |
+----+-------+---------+-------------+
1 row in set (0.00 sec)
0
0
0
s2smodern