br.com.hslife.catu.db.HibernateUtil.java Source code

Java tutorial

Introduction

Here is the source code for br.com.hslife.catu.db.HibernateUtil.java

Source

/***
    
Copyright (c) 2010-2014 Hrcules S. S. Jos
    
    
    
Este arquivo  parte do programa CATU.
    
CATU  um software livre; voc pode redistribui-lo e/ou 
    
modific-lo dentro dos termos da Licena Pblica Geral Menor GNU como 
    
publicada pela Fundao do Software Livre (FSF); na verso 2.1 da 
    
Licena.
    
    
    
Este programa  distribudo na esperana que possa ser til, 
    
mas SEM NENHUMA GARANTIA; sem uma garantia implicita de ADEQUAO a qualquer
    
MERCADO ou APLICAO EM PARTICULAR. Veja a Licena Pblica Geral Menor GNU 
    
em portugus para maiores detalhes.
    
    
    
Voc deve ter recebido uma cpia da Licena Pblica Geral Menor GNU sob o 
    
nome de "LICENSE.TXT" junto com este programa, se no, acesse o site HSlife no 
    
endereco www.hslife.com.br ou escreva para a Fundao do Software Livre(FSF) Inc., 
    
51 Franklin St, Fifth Floor, Boston, MA  02110-1301, USA.
    
    
    
Para mais informaes sobre o programa CATU e seus autores acesse o 
    
endereo www.hslife.com.br, pelo e-mail contato@hslife.com.br ou escreva para 
    
Hrcules S. S. Jos, Av. Ministro Lafaeyte de Andrade, 1683 - Bl. 3 Apt 404, 
    
Marco II - Nova Iguau, RJ, Brasil.
    
***/

package br.com.hslife.catu.db;

import java.sql.Connection;

import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.CacheMode;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

/**
 * Hibernate Utility class with a convenient method to get Session Factory object.
 *
 * @author Hrcules
 */
public class HibernateUtil {
    /*
     private static SessionFactory sessionFactory;
        
     static {
    try {
        // Create the SessionFactory from standard (hibernate.cfg.xml)
        // config file.
        sessionFactory = new AnnotationConfiguration()
                .configure("br/com/hslife/catu/db/hibernate.cfg.xml")
                .buildSessionFactory();
    } catch (Throwable ex) {
        // Log the exception.
        System.err.println("Initial SessionFactory creation failed." + ex);
        throw new ExceptionInInitializerError(ex);
    }
     }
        
     public static SessionFactory getSessionFactory() {
    if (sessionFactory == null || sessionFactory.isClosed()) {
       try {
            // Create the SessionFactory from standard (hibernate.cfg.xml)
            // config file.
            sessionFactory = new AnnotationConfiguration()
                    .configure("br/com/hslife/catu/db/hibernate.cfg.xml")
                    .buildSessionFactory();
        } catch (Throwable ex) {
            // Log the exception.
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }
    return sessionFactory;
     }
     */

    private static final SessionFactory sessionFactory;
    private static final ThreadLocal<Session> sessionThread = new ThreadLocal<Session>();
    private static final ThreadLocal<Transaction> transactionThread = new ThreadLocal<Transaction>();

    static {
        try {
            sessionFactory = new AnnotationConfiguration().configure("br/com/hslife/catu/db/hibernate.cfg.xml")
                    .buildSessionFactory();
        } catch (RuntimeException e) {
            e.printStackTrace();
            throw e;
        }
    }

    public static Session getSession() {
        if (sessionThread.get() == null) {
            Session session = sessionFactory.openSession();
            session.setCacheMode(CacheMode.IGNORE);
            sessionThread.set(session);
            System.out.println("Nova sesso criada");
        }
        return (Session) sessionThread.get();
    }

    public static Connection getConnection() {
        return getSession().connection();
    }

    public static void closeSession() {
        Session session = (Session) sessionThread.get();
        if (session != null && session.isOpen()) {
            sessionThread.set(null);
            session.close();
            System.out.println("Sesso atual fechada");
        }
    }

    public static void beginTransaction() {
        Transaction transaction = getSession().beginTransaction();
        transactionThread.set(transaction);
        System.out.println("Transacao iniciada");
    }

    public static void commitTransaction() {
        Transaction transaction = (Transaction) transactionThread.get();
        if (transaction != null && !transaction.wasCommitted() && !transaction.wasRolledBack()) {
            transaction.commit();
            transactionThread.set(null);
            System.out.println("Transao finalizada com sucesso");
        }
    }

    public static void rollbackTransaction() {
        Transaction transaction = (Transaction) transactionThread.get();
        if (transaction != null && !transaction.wasCommitted() && !transaction.wasRolledBack()) {
            transaction.rollback();
            transactionThread.set(null);
            System.out.println("Transacao finalizada com falha. Alteraoes desfeitas");
        }
    }
}