All Downloads are FREE. Search and download functionalities are using the official Maven repository.

se.wfh.libs.common.web.util.HibernateUtil Maven / Gradle / Ivy

package se.wfh.libs.common.web.util;

import java.io.File;
import java.io.Serializable;
import java.sql.SQLException;
import java.util.Set;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import se.wfh.libs.common.web.exceptions.WebException;

import com.mchange.v2.c3p0.C3P0Registry;
import com.mchange.v2.c3p0.PooledDataSource;

public final class HibernateUtil implements Serializable {
	private static final long serialVersionUID = 1L;
	private static final Logger LOGGER = LoggerFactory
			.getLogger(HibernateUtil.class);

	private static SessionFactory SESSION_FACTORY = null;

	public static void init(String appId) {
		LOGGER.info("Configuring hibernate.");
		Configuration configuration = new Configuration();

		File configFile = new File(FacesTools.CONFIG_DIR + File.separator + appId,
				"hibernate.cfg.xml");

		configuration.configure(configFile);
		ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
				.applySettings(configuration.getProperties()).build();
		SESSION_FACTORY = configuration.buildSessionFactory(serviceRegistry);
		LOGGER.info("Hibernate configuration finished.");
	}

	public static void destroy() {
		if (SESSION_FACTORY == null) {
			return;
		}

		LOGGER.info("Closing hibernate factory.");
		SESSION_FACTORY.close();

		try {
			PooledDataSource ds = findUniqueDataSource();
			if (ds != null) {
				LOGGER.info("Closing c3p0 datasource.");

				ds.close();
			}
		} catch (WebException | SQLException sex) {
			LOGGER.error("Error closing datasource.");
			LOGGER.debug(sex.getLocalizedMessage(), sex);
		}
	}

	@SuppressWarnings("unchecked")
	private static PooledDataSource findUniqueDataSource() throws WebException {
		Set set = C3P0Registry.getPooledDataSources();
		int poolSize = set.size();
		if (poolSize == 1) {
			return set.iterator().next();
		} else if (poolSize != 0) {
			throw new WebException("No unique c3p0 DataSource, found: " + poolSize);
		}

		return null;
	}

	public static Session getSession() {
		return SESSION_FACTORY.getCurrentSession();
	}

	private HibernateUtil() {
	}
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy