This example has been taken from here
package com.reborne.SmartHibernateConnector.utils;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class LiveHibernateConnector implements IHibernateConnector {
private String DB_DRIVER_NAME = "";
private String DB_URL = "jdbc:h2:~/liveDB;MV_STORE=FALSE;MVCC=FALSE";
private String DB_USERNAME = "sa";
private String DB_PASSWORD = "";
private String DIALECT = "org.hibernate.dialect.H2Dialect";
private String HBM2DLL = "create";
private String SHOW_SQL = "true";
private static Configuration config;
private static SessionFactory sessionFactory;
private Session session;
private boolean CLOSE_AFTER_TRANSACTION = false;
public LiveHibernateConnector() {
config = new Configuration();
config.setProperty("hibernate.connector.driver_class", DB_DRIVER_NAME);
config.setProperty("hibernate.connection.url", DB_URL);
config.setProperty("hibernate.connection.username", DB_USERNAME);
config.setProperty("hibernate.connection.password", DB_PASSWORD);
config.setProperty("hibernate.dialect", DIALECT);
config.setProperty("hibernate.hbm2dll.auto", HBM2DLL);
config.setProperty("hibernate.show_sql", SHOW_SQL);
/*
* Config connection pools
*/
config.setProperty("connection.provider_class", "org.hibernate.connection.C3P0ConnectionProvider");
config.setProperty("hibernate.c3p0.min_size", "5");
config.setProperty("hibernate.c3p0.max_size", "20");
config.setProperty("hibernate.c3p0.timeout", "300");
config.setProperty("hibernate.c3p0.max_statements", "50");
config.setProperty("hibernate.c3p0.idle_test_period", "3000");
/**
* Resource mapping
*/
// config.addAnnotatedClass(User.class);
// config.addAnnotatedClass(User.class);
// config.addAnnotatedClass(User.class);
sessionFactory = config.buildSessionFactory();
}
public HibWrapper openSession() throws HibernateException {
return new HibWrapper(getOrCreateSession(), CLOSE_AFTER_TRANSACTION);
}
public Session getOrCreateSession() throws HibernateException {
if (session == null) {
session = sessionFactory.openSession();
}
return session;
}
public void reconnect() throws HibernateException {
this.sessionFactory = config.buildSessionFactory();
}
}
Please note, that with latest Hibernate this approach doesn't work well (Hibernate 5.2 release still allow this configuration)