com.daniel.testehibernate.conexao.HibernateUtil.java Source code

Java tutorial

Introduction

Here is the source code for com.daniel.testehibernate.conexao.HibernateUtil.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.daniel.testehibernate.conexao;

import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;

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

    private static final SessionFactory sessionFactory = buildSessionFactory();

    private static SessionFactory buildSessionFactory() {
        try {
            Configuration cfg = new Configuration();
            cfg.configure("hibernate.cfg.xml");
            StandardServiceRegistryBuilder registradorService = new StandardServiceRegistryBuilder();
            registradorService.applySettings(cfg.getProperties());
            StandardServiceRegistry servico = registradorService.build();
            return cfg.buildSessionFactory(servico);
        } catch (Exception e) {
            System.err.println("Criao inicial do objeto session factory falhou. Erro:" + e);
            throw new ExceptionInInitializerError(e);
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }

}