Java
  Home arrow Java arrow Page 4 - 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  
Mobile Linux 
App Generation ROI 
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 / 31
    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 - 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.

       · 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 3 hosted by Hostway
    Stay green...Green IT