org.balisunrise.daa.hibernate.HibernateUtil.java Source code

Java tutorial

Introduction

Here is the source code for org.balisunrise.daa.hibernate.HibernateUtil.java

Source

/*
 * Copyright (C) 2015 Glauco Knihs. All rights reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * Please contact Glauco Knihs, Rua 10 de Junho, N469, Centro, 
 * Guabiruba-SC, CEP 88360-000, BRAZIL, eglauko@hotmail.com, 
 * if you need additional information or have any questions.
 */
package org.balisunrise.daa.hibernate;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import java.util.Properties;
import org.hibernate.SessionFactory;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;

/**
 * Hibernate Utility class with a convenient method to get Session Factory
 * object.
 *
 * @author Glauco Knihs
 */
public class HibernateUtil {

    private static StandardServiceRegistryBuilder builder;
    private static StandardServiceRegistry registry;
    private static MetadataSources metadata;
    private static SessionFactory sessionFactory;

    /**
     * Nome do arquivo de Configurao do Hibernate do formato properties.
     */
    public static String PROPERTIES_CONFIG_FILE = "hibernate.properties";

    /**
     * Propriedades das configuraes.
     */
    private static Properties hibernateProperties;

    /**
     * Classes de Entidades.
     */
    private static List<Class> classes = new LinkedList<>();

    static {
        try {
            // A SessionFactory is set up once for an application!
            start();
            //setUp();
        } catch (Throwable ex) {
            // Log the exception. 
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    private static void start() throws Exception {
        builder = new StandardServiceRegistryBuilder();
        builder.applySettings(loadProperties());
    }

    private static void setUp() throws Exception {

        registry = builder.build();
        try {
            metadata = new MetadataSources(registry);
            classes.stream().forEach(c -> metadata.addAnnotatedClass(c));
            sessionFactory = metadata.buildMetadata().buildSessionFactory();
        } catch (Exception e) {
            // The registry would be destroyed by the SessionFactory,
            // but we had trouble building the SessionFactory
            // so destroy it manually.
            StandardServiceRegistryBuilder.destroy(registry);
            registry = null;
            metadata = null;
            sessionFactory = null;
            throw e;
        }
    }

    /**
     * Close caches and connection pools.
     */
    private static void shutdown() {
        if (sessionFactory != null) {
            sessionFactory.close();
            sessionFactory = null;
        }
        if (registry != null) {
            StandardServiceRegistryBuilder.destroy(registry);
            registry = null;
        }
        metadata = null;
    }

    private static Properties loadProperties() throws Exception {
        if (hibernateProperties == null) {
            String fileName = org.balisunrise.rua.Configuration.classPath(HibernateUtil.class)
                    + PROPERTIES_CONFIG_FILE;
            File file = new File(fileName);
            if (file.exists()) {
                try {
                    Properties p = new Properties();
                    p.load(new FileInputStream(file));
                    hibernateProperties = p;
                } catch (IOException ex) {
                    // no leu arquivo
                    file.delete();
                }
            } else {
                Properties p = new Properties();
                p.setProperty("hibernate.connection.driver_class", "org.postgresql.Driver");
                p.setProperty("hibernate.connection.url", "jdbc:postgresql://localhost:5432/balisunrise");
                p.setProperty("hibernate.connection.username", "postgres");
                p.setProperty("hibernate.connection.password", "master");
                p.setProperty("hibernate.dialect", "org.hibernate.dialect.PostgreSQLDialect");
                p.setProperty("show_sql", "true");
                p.setProperty("format_sql", "true");
                p.setProperty("hibernate.c3p0.min_size", "5");
                p.setProperty("hibernate.c3p0.max_statements", "100");
                p.setProperty("hibernate.hbm2ddl.auto", "update");
                //p.setProperty("", "");
                try {
                    p.store(new FileOutputStream(file), "Propriedades do Hibernate");
                } catch (Exception ex) {
                    System.out.println(ex.getMessage());
                }
                hibernateProperties = p;
            }
        }
        return hibernateProperties;
    }

    /**
     * Adiciona um array de classes nas configuraes e cria um novo
     * sessionFactoty para futuras classes.
     *
     * @param classes Arrat de classes para serem mapeadas.
     */
    public static void addClasses(Class[] classes) {

        if (classes == null) {
            return;
        }

        boolean shutdown = false;

        for (Class c : classes) {
            if (HibernateUtil.classes.contains(c)) {
                continue;
            }
            HibernateUtil.classes.add(c);
            shutdown = true;
        }

        if (shutdown) {
            shutdown();
        }
    }

    public static SessionFactory getSessionFactory() {
        if (sessionFactory == null) {
            try {
                setUp();
            } catch (Exception ex) {
                System.err.println("Initial SessionFactory creation failed." + ex);
                throw new ExceptionInInitializerError(ex);
            }
        }
        return sessionFactory;
    }
}