Java
  Home arrow Java arrow Page 3 - Managing Transactions with Hibernate
Dev Articles Forums 
ADO.NET  
Apache  
ASP  
ASP.NET  
C#  
C++  
ColdFusion  
COM/COM+  
Delphi-Kylix  
Design Usability  
Development Cycles  
DHTML  
Embedded Tools  
Flash  
Graphic Design  
HTML  
IIS  
Interviews  
Java  
JavaScript  
MySQL  
Oracle  
Photoshop  
PHP  
Reviews  
Ruby-on-Rails  
SQL  
SQL Server  
Style Sheets  
VB.Net  
Visual Basic  
Web Authoring  
Web Services  
Web Standards  
XML  
Moblin 
JMSL Numerical Library 
IBM® developerWorks 
Sun Developer Network 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
JAVA

Managing Transactions with Hibernate
By: A.P.Rajshekhar
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 5 stars5 stars5 stars5 stars5 stars / 30
    2006-04-19

    Table of Contents:
  • Managing Transactions with Hibernate
  • Transactions: Core APIs
  • Hibernate in the Real World: Implementing a Utility class for Hibernate
  • Implementing a Utility class for Hibernate continued

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT


    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.

    More Java Articles
    More By A.P.Rajshekhar


       · Transaction control is the base of database based programming where concurrent...
       · Dear Sir/ Madam, I am using the same pattern for transaction commit, when I keep...
     

    JAVA ARTICLES

    - 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 ...
    - Generics and Limitations in Java
    - Getting Started with Java Web Development in...






    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 6 hosted by Hostway
    Stay green...Green IT