it.unitn.elisco.utils.HibernateUtil.java Source code

Java tutorial

Introduction

Here is the source code for it.unitn.elisco.utils.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 it.unitn.elisco.utils;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.Metadata;
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 Andrea Marcolin
 */
public class HibernateUtil {
    private static final SessionFactory SESSION_FACTORY = buildSessionFactory();

    private static SessionFactory buildSessionFactory() {
        try {
            StandardServiceRegistry standardRegistry = new StandardServiceRegistryBuilder()
                    .applySetting("hibernate.hikari.dataSource.url",
                            ConfigurationProperties.getInstance().getDbURL())
                    .applySetting("hibernate.hikari.dataSource.user",
                            ConfigurationProperties.getInstance().getDbUsername())
                    .applySetting("hibernate.hikari.dataSource.password",
                            ConfigurationProperties.getInstance().getDbPassword())
                    .configure("hibernate.cfg.xml").build();

            Metadata metadata = new MetadataSources(standardRegistry).getMetadataBuilder().build();

            return metadata.getSessionFactoryBuilder().build();
        } catch (Throwable ex) {
            throw new ExceptionInInitializerError(ex);
        }
    }

    private static SessionFactory getSessionFactory() {
        return SESSION_FACTORY;
    }

    public static void closeSessionFactory() {
        SESSION_FACTORY.close();
    }

    public static Session getSession() {
        return getSessionFactory().openSession();
    }

}