Hibernate Tutorial : Part 2

Now we continue on the next step (go through Part 1 before reading this). Here I will explain about the configurations and how to work with Hibernate.

Hibernate is designed to operate in different types on environment, thus there are a lots of configuration parameters. For this tutorial, we only use some basic configuration parameters just to make it work. There are 3 types of configurations (programmatic configuration, XML configuration and properties file configuration). Here, we will use XML configuration. The configuration file need to be placed in the root of your CLASSPATH and named with “hibernate.cfg.xml“.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
    <session-factory>
<property name="hibernate.connection.driver_class">org.gjt.mm.mysql.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost/hbm</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">true</property>

        <mapping resource="com/training/Risk.hbm.xml"/>
        <mapping resource="com/training/Policy.hbm.xml"/>
        <mapping resource="com/training/Client.hbm.xml"/>
        <mapping resource="com/training/Batch.hbm.xml"/>
    </session-factory>

</hibernate-configuration>

The most important thing here is your session factory. A global SessionFactory object will be instantiated and used by Hibernate to do the database operations. Inside the session factory, we need to define the data source and your mapping file location (you can add more configurations if needed). SessionFactory object will only be instantiated once. It can open new Session that represents a single-threaded unit of work.

In order to instantiate the session factory, we need a helper class (named as HibernateUtil.java) that handle the startup and makes accessing a SessionFactory convenient.

public class HibernateUtil {
    private static final SessionFactory sessionFactory;
    static {
        try {
            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 Session getSession() {
        return sessionFactory.openSession();
    }
}

Here, we will use a Data Access Object (DAO) to abstract and encapsulate all access to the data source. The DAO manages the connection with the data source to obtain and store data. The DAO implements the access mechanism required to work with the data source. Below is the implementation of the DAO that we be used.

public class PolicyDAOImpl implements PolicyDAO {

    public void add(Policy policy) {
        Session session = HibernateUtil.getSession();
        try{
            Transaction tx = session.beginTransaction();
            session.save(policy);
            tx.commit();
        }finally{
            session.close();
        }
    }

    public void update(Policy policy) {
        Session session = HibernateUtil.getSession();
        try{
            Transaction tx = session.beginTransaction();
            session.update(policy);
            tx.commit();
        }finally{
            session.close();
        }
    }

    public void delete(Policy policy) {
        Session session = HibernateUtil.getSession();
        try{
            Transaction tx = session.beginTransaction();
            session.delete(policy);
            tx.commit();
        }finally{
            session.close();
        }
    }

    public Policy get(int policyNo) {
        Session session = HibernateUtil.getSession();
        Policy policy = null;

        try{
            Transaction tx = session.beginTransaction();
            policy = (Policy)session.get(Policy.class, new Integer(policyNo));
            Hibernate.initialize(new Integer(policy.getPolicyNo()));
            tx.commit();
        }finally{
            session.close();
        }

        return policy;
    }

    public List getAll() {
        Session session = HibernateUtil.getSession();
        Transaction tx = null;
        List result = null;
        try {
            tx = session.beginTransaction();
            Query q = session.createQuery("from Policy");
            result = q.list();
            tx.commit();
        }
        catch (HibernateException he) {
            if (tx!=null) tx.rollback();
            throw he;
        }
        finally {
            session.close();
        }
        return result;
    }
}

As you can see here, all method need to get new Session from SessionFactory. To shield our code from the actual underlying transaction system (in this case plain JDBC, but it could also run with JTA) we use the Transaction API that is available on the Hibernate Session. When the transaction ends, either committed or rolled back, Hibernate also unbinds the Session from the thread and closes it for you.

I want to highlight something here. What we do for getAll() method is use an HQL (Hibernate Query Language) query to load all existing Policy objects from the database. Hibernate will generate the appropriate SQL (based on your specified dialect), send it to the database and populate Policy objects with the data. You can create more complex queries with HQL, of course.

Now, we can start working with Hibernate. You can create a class with a main() method to test the DAO.

Source code: Get it here

Reference: Hibernate Reference Documentation

-HADZRUL-

Respond to this post