Java tutorial
/* * 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.tests.hibernate; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; 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 * @version 1.0 * @since 1.0 */ 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(); String fileName = org.balisunrise.rua.Configuration.classPath(HibernateUtil.class) + StandardServiceRegistryBuilder.DEFAULT_CFG_RESOURCE_NAME; File f = new File(fileName); if (f.exists()) { builder.configure(); } else { 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. */ public static void shutdown() { if (sessionFactory != null) { sessionFactory.close(); sessionFactory = null; } if (registry != null) { StandardServiceRegistryBuilder.destroy(registry); registry = null; } metadata = null; } public static Map<String, String> loadMap() { HashMap<String, String> resultMap = new HashMap<>(); try { Properties ps = loadProperties(); ps.keySet().stream().map((prop) -> (String) prop).forEach((name) -> { String value = (String) ps.getProperty(name); resultMap.put(name, value); }); } catch (Exception ex) { System.err.println("Initial Properties failed.\n" + ex); throw new ExceptionInInitializerError(ex); } return resultMap; } public 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)); System.out.println("Carregadas propriedades para o hibernate do arquivo: " + file.getName()); hibernateProperties = p; return p; } catch (IOException ex) { // no leu arquivo file.delete(); } } Properties p = new Properties(); p.setProperty("hibernate.connection.driver_class", "org.postgresql.Driver"); p.setProperty("hibernate.connection.url", "jdbc:postgresql://localhost:5432/aplicativo"); 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()); } System.out.println("Carregadas propriedades padro do hibernate"); 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.\n" + ex); throw new ExceptionInInitializerError(ex); } } return sessionFactory; } }