Home arrow Java arrow Page 3 - Managing Transactions with Hibernate
JAVA

Managing Transactions with Hibernate


This article explains how Hibernate handles sessions and transactions, and why those are important to a database-based applications. It also explains how core APIs take part in session and transaction management, and more.

Author Info:
By: A.P.Rajshekhar
Rating: 4 stars4 stars4 stars4 stars4 stars / 85
April 19, 2006
TABLE OF CONTENTS:
  1. · Managing Transactions with Hibernate
  2. · Transactions: Core APIs
  3. · Hibernate in the Real World: Implementing a Utility class for Hibernate
  4. · Implementing a Utility class for Hibernate continued

print this article
SEARCH DEVARTICLES

Managing Transactions with Hibernate - Hibernate in the Real World: Implementing a Utility class for Hibernate
(Page 3 of 4 )

Until now I've been creating the configuration, building the session and retrieving the transaction object whenever a requirement arose. Though in the last part the CRUD related functionality was shifted to a separate class, the steps needed to initialize the Hibernate framework were not modularized or made generic so that they could be reused. That is what I am going to do in this section. But before going ahead with the utility class, one more concept has to be introduced: Thread Local Variables.

These variables differ from their normal counterparts in that each thread that accesses one (via its get or set method) has its own, independently initialized copy of the variable. ThreadLocal instances are typically private static fields in classes that wish to associate state with a thread (e.g., a user ID or transaction ID). In short, threads would have their own copy of the thread local variables. While its true that there would be only one ThreadLocal variable, that variable would hold multiple instances of the desired object. In our case that would be the session object.

Now that I've given you an overview of the concept of a Thread Local Variable, let's get started with the implementation details of the Hibernate utility class. For the sake of convention it has been name HibernateUtility. 

First comes the package name and imports:

package com.someorg.persist;

import org.hibernate.*;
import org.hibernate.cfg.*;

Next come the class

public class HibernateUtility {
:
:
}

Since the class is following the factory pattern, all the methods would be static and there would be no constructor as such. Here I would like to point out that there can be varied implementation of a pattern. There is no hard and fast implementation of any pattern. Also the initializations are done in a static block:

public class HibernateUtility {

public 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);
        }
    }

:
:
}

Then comes the thread local variable:

public class HibernateUtility {

public 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 final ThreadLocal session = new
ThreadLocal();

:
:
}

Now come the methods that provide session management.

public class HibernateUtility {

public 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 final ThreadLocal session = new ThreadLocal();

 public static Session currentSession() throws
HibernateException
 
{
        Session s = (Session) session.get();
        // Open a new Session, if this thread has none
yet
        if (s == null) {
            s = sessionFactory.openSession();
            // Store it in the ThreadLocal variable
            session.set(s);
        }
        return s;
    }

    public static void closeSession() throws
HibernateException {
        Session s = (Session) session.get();
        if (s != null)
            s.close();
        session.set(null);
    }

:
:
}

Each new session object is set as the Thread Local Variable. Whenever the session has to be closed, the appropriate session object is retrieved from the thread and it is closed.


blog comments powered by Disqus
JAVA ARTICLES

- Java Too Insecure, Says Microsoft Researcher
- Google Beats Oracle in Java Ruling
- Deploying Multiple Java Applets as One
- Deploying Java Applets
- Understanding Deployment Frameworks
- Database Programming in Java Using JDBC
- Extension Interfaces and SAX
- Entities, Handlers and SAX
- Advanced SAX
- Conversions and Java Print Streams
- Formatters and Java Print Streams
- Java Print Streams
- Wildcards, Arrays, and Generics in Java
- Wildcards and Generic Methods in Java
- Finishing the Project: Java Web Development ...

Watch our Tech Videos 
Dev Articles Forums 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Contact Us 
Site Map 
Privacy Policy 
Support 

Developer Shed Affiliates

 




© 2003-2017 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap
Popular Web Development Topics
All Web Development Tutorials