Home arrow Java arrow Page 4 - 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 - Implementing a Utility class for Hibernate continued
(Page 4 of 4 )

Finally, here are the factory methods for transaction control.

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 getSession() 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);
    }
/**
     * @return the hibernate session factory
     */
    public static SessionFactory getSessionFactory( ) {
      return factory;
    }

/**
     * This is a simple method to reduce the amount of
code that needs
     * to be written every time hibernate is used.
     */
    public static void rollback(org.hibernate.Transaction
tx) {
        if (tx != null) {
            try {
                tx.rollback( );
            }
            catch (HibernateException ex) {
                // Probably don't need to do anything -
this is likely being
                // called because of another exception,
and we don't want to
                // mask it with yet another exception.
            }
        }
    }
/**
     * This is a simple method to reduce the amount of
code that needs
     * to be written every time hibernate is used.
     */
    public static void commit(org.hibernate.Transaction tx) {
        if (tx != null) {
            try {
                tx.commit( );
            }
            catch (HibernateException ex) {
                // Probably don't need to do anything -
this is likely being
                // called because of another exception,
and we don't want to
                // mask it with yet another exception.
            }
        }
    }

}

This class can be used in both standalone as well as Web mode. If you're using it as a web application, care should be taken to put the configuration files in a classes folder.

If we rewrite the application of the previous part using the just created Hibernate utility, it would be as follows:

package com.someorg.persist.op;

import java.util.List;
import com.someorg.persist.*;
import org.hibernate.Hibernate;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import com.someorg.persist.Order
import 
org.hibernate.*;
import org.hibernate.criterion.*;

public class OrderOP {

HibernateFactory sf;

public OrderOP(){
         }         

          public Order getOrder(String lower, String upper){
                   // open session
Session sess = sf.getSession();

//The following code has been commented so that
//comparison between HQL and Criteria Query

/*String query = "select o from o "
    + "Order as o join o.products as p "
    + "where o.priceTotal > :priceTotalLower "
    + "and o.priceTotal < :priceTotalUpper";         

Query q = sess.createQuery(query);
q.setDouble("priceTotalLower", 
             Double.parseDouble(lower));

q.setDouble("priceTotalUpper", 
             Double.parseDouble(upper));
                    */
List list = sess.createCriteria(Order.class)
                        .add(Restrictions.between(lower,upper)
                        . list();

Order o=(Order)list.iterator.next();
sf.closeSession();
return o;
           }

          public static void main(String args[]){
                     Order o=OrderOP().getOrder
(“2000’,”3000”);                 

                     System.out.println(“Order Id:”+ o.id);
                     //and so on
          }
}

All the initialization aspects have been wrapped up in the utility class. So it has become really simple. That brings us to the end of this discussion. Understanding how transactions are managed is just beginning of understanding the layers of Hibernate. In the next part I will be discussing advanced mapping concepts. Till then…


DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

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