Example usage for org.hibernate.cfg Configuration buildSessionFactory

List of usage examples for org.hibernate.cfg Configuration buildSessionFactory

Introduction

In this page you can find the example usage for org.hibernate.cfg Configuration buildSessionFactory.

Prototype

public SessionFactory buildSessionFactory() throws HibernateException 

Source Link

Document

Create a SessionFactory using the properties and mappings in this configuration.

Usage

From source file:de.phoenix.database.DatabaseManager.java

License:Open Source License

private DatabaseManager() {
    Configuration config = new Configuration().configure("hibernate.cfg.xml");
    this.sessionFactory = config.buildSessionFactory();
}

From source file:de.unisb.cs.st.javalanche.mutation.util.HibernateServerUtil.java

License:Open Source License

private static SessionFactory getServerConnection(Server s) {
    SessionFactory sessionFactory = null;
    try {//  w  w  w.  j  ava2  s .c o  m
        AnnotationConfiguration annotationConfiguration = new AnnotationConfiguration();
        Configuration configuration = annotationConfiguration.configure();
        // String property1 = configuration
        // .getProperty(HIBERNATE_CONNECTION_URL);
        configuration.setProperty(HIBERNATE_CONNECTION_URL, s.getConnection());
        // String property2 = configuration
        // .getProperty(HIBERNATE_CONNECTION_URL);
        // System.err.println(property2);
        // System.err.println(property1.equals(property2));
        sessionFactory = configuration.buildSessionFactory();
        sessionFactories.put(s, sessionFactory);
    } catch (Throwable ex) {
        ex.printStackTrace();
        throw new ExceptionInInitializerError(ex);
    }
    return sessionFactory;
}

From source file:dms.Persist.java

private void setUp() {
    Configuration c = new Configuration();
    c.configure();
    sf = c.buildSessionFactory();
}

From source file:edu.jhuapl.dorset.components.HibernateService.java

License:Open Source License

/**
 * Create the hibernate service which initializes the session factory
 *
 * @param conf  application configuration
 * @throws UnsupportedOperationException if a mapping file is invalid
 *//*from w ww  .jav  a2  s . co m*/
public HibernateService(Config conf) {
    Configuration hibernateConf = new Configuration();
    Config hc = conf.getConfig(HIBERNATE_KEY).atPath(HIBERNATE_KEY);
    for (Map.Entry<String, ConfigValue> entry : hc.entrySet()) {
        String key = entry.getKey();
        if (key.startsWith(MAPPING_KEY)) {
            logger.info("Loading hibernate map from " + conf.getString(key));
            try {
                hibernateConf.addResource(conf.getString(key));
            } catch (MappingException e) {
                String msg = "Something wrong with mapping: " + conf.getString(key);
                throw new UnsupportedOperationException(msg, e);
            }
        } else {
            logger.info("Setting hibernate property: " + key + "=" + conf.getString(key));
            hibernateConf.setProperty(key, conf.getString(key));
        }
    }
    sessionFactory = hibernateConf.buildSessionFactory();
}

From source file:edu.jhuapl.dorset.reporting.SqlReporterTest.java

License:Open Source License

@Before
public void setup() {
    Configuration conf = new Configuration();
    conf.setProperty("hibernate.connection.driver_class", "org.h2.Driver");
    conf.setProperty("hibernate.connection.url", "jdbc:h2:mem:sql_reporter");
    conf.setProperty("hibernate.connection.pool_size", "1");
    conf.setProperty("hibernate.dialect", "org.hibernate.dialect.H2Dialect");
    conf.setProperty("hibernate.hbm2ddl.auto", "create-drop");
    conf.addResource("report.hbm.xml");
    sessionFactory = conf.buildSessionFactory();
}

From source file:edu.kit.ipd.sonar.server.HibernateUtil.java

License:Open Source License

/**
 * Rebuilds session factory. Closes old session factory and creates a new
 * one depending on a new hibernate configuration file.
 *
 * @param config/*from  w w  w  . ja  v a2 s .  co  m*/
 *            new configuration for the session factory
 */
static void rebuildSessionFactory(final org.hibernate.cfg.Configuration config) {
    log.debug("Rebuilding the Hibernate Session Factory from new Config");
    if (sessionFactory != null && !sessionFactory.isClosed()) {
        /* if still open, close current session factory */
        sessionFactory.close();
    }
    /* build a new session factory and update static config */
    try {
        sessionFactory = config.buildSessionFactory();
    } catch (Exception e) {
        if (e instanceof java.sql.SQLException) {
            log.error("Building Hibernate Session failed due to" + " an SQLExeption: " + e.getMessage());
        } else {
            log.error("Building Hibernate Session failed due to" + " some unexpected Behaviour: "
                    + e.getMessage());
        }
        throw new HibernateException("Database Conenction could not be" + "instantiated.");
    }

    configuration = config;
}

From source file:edu.ku.brc.dbsupport.HibernateUtil.java

License:Open Source License

/**
 * Rebuild the SessionFactory with the given Hibernate Configuration.
 * <p>/*from   ww w  .j ava  2 s . c  o m*/
 * HibernateUtil does not configure() the given Configuration object,
 * it directly calls buildSessionFactory(). This method also closes
 * the old SessionFactory before, if still open.
 *
 * @param cfg
 */
public static void rebuildSessionFactory(final Configuration cfg) {
    //log.debug("Rebuilding the SessionFactory from given Configuration.");
    synchronized (sessionFactory) {
        if (sessionFactory != null && !sessionFactory.isClosed()) {
            sessionFactory.close();
        }
        if (cfg.getProperty(Environment.SESSION_FACTORY_NAME) != null) {
            cfg.buildSessionFactory();
        } else {
            sessionFactory = cfg.buildSessionFactory();
        }
        configuration = cfg;
    }
}

From source file:edu.northwestern.bioinformatics.studycalendar.security.csm.internal.DefaultCsmAuthorizationManagerFactory.java

License:BSD License

private SessionFactory createCsmSessionFactory() throws Exception {
    Configuration hibConf = new DefaultCsmHibernateConfiguration();

    // these paths are copied straight from CSM's ApplicationSessionFactory
    String[] mappingPaths = {/*from  w w w  . j av a2  s. c o m*/
            "gov/nih/nci/security/authorization/domainobjects/InstanceLevelMappingElement.hbm.xml",
            "gov/nih/nci/security/authorization/domainobjects/Privilege.hbm.xml",
            "gov/nih/nci/security/authorization/domainobjects/Application.hbm.xml",
            "gov/nih/nci/security/authorization/domainobjects/FilterClause.hbm.xml",
            "gov/nih/nci/security/authorization/domainobjects/Role.hbm.xml",
            "gov/nih/nci/security/dao/hibernate/RolePrivilege.hbm.xml",
            "gov/nih/nci/security/dao/hibernate/UserGroup.hbm.xml",
            "gov/nih/nci/security/dao/hibernate/ProtectionGroupProtectionElement.hbm.xml",
            "gov/nih/nci/security/authorization/domainobjects/Group.hbm.xml",
            "gov/nih/nci/security/authorization/domainobjects/User.hbm.xml",
            "gov/nih/nci/security/authorization/domainobjects/ProtectionGroup.hbm.xml",
            "gov/nih/nci/security/authorization/domainobjects/ProtectionElement.hbm.xml",
            "gov/nih/nci/security/authorization/domainobjects/UserGroupRoleProtectionGroup.hbm.xml",
            "gov/nih/nci/security/authorization/domainobjects/UserProtectionElement.hbm.xml" };
    for (String mappingPath : mappingPaths) {
        hibConf.addResource(mappingPath, AuthorizationManager.class.getClassLoader());
    }

    ClassLoader originalContextCL = Thread.currentThread().getContextClassLoader();
    try {
        Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader());
        // this cast is endorsed by the Hibernate 3.6 Core docs as one of the two mechanisms to
        // add an entity name resolver.
        SessionFactoryImpl sessionFactory = (SessionFactoryImpl) hibConf.buildSessionFactory();
        sessionFactory.registerEntityNameResolver(new CglibProxyEntityNameResolver(), EntityMode.POJO);
        return sessionFactory;
    } finally {
        Thread.currentThread().setContextClassLoader(originalContextCL);
    }
}

From source file:edu.pitt.dbmi.deepphe.summarization.orm.i2b2data.I2b2DataDataSourceManager.java

@SuppressWarnings("deprecation")
private boolean buildSessionFactory(Configuration configuration) {
    sessionFactory = configuration.buildSessionFactory();
    return !sessionFactory.isClosed();
}

From source file:edu.pitt.dbmi.facebase.hd.MySQLHibernateConfiguration.java

License:Open Source License

private SessionFactory getSessionFactory() {
    log.debug("MySQLHibernateConfiguration.getSessionFactory() called ");
    if (lclSessionFactory != null)
        return (lclSessionFactory);

    try {/*from  www.  j a v a 2  s .  c  o m*/
        boolean validConnection = false;
        try {
            DriverManager.registerDriver(new com.mysql.jdbc.Driver());
            Connection conn = DriverManager.getConnection(connectionURL, username, password);
            conn.close();
            validConnection = true;
        } catch (Exception e) {
            String errorString = "Cannot connect to database at " + connectionURL + " with username " + username
                    + e.toString();
            String logString = e.getMessage();
            edu.pitt.dbmi.facebase.hd.HumanDataController.addError(errorString, logString);
            log.error(errorString, e);
            edu.pitt.dbmi.facebase.hd.HumanDataController.reportDbConnectionFailure();
            return (null);
        }

        if (validConnection) {
            Configuration hibernateConf = null;
            hibernateConf = new Configuration();
            String className = null;
            try {
                hibernateConf.addAnnotatedClass(InstructionQueueItem.class);
            } catch (Exception ex) {
                String errorString = "Unable to load annotated class for hibernate: " + className
                        + ex.toString();
                String logString = ex.getMessage();
                edu.pitt.dbmi.facebase.hd.HumanDataController.addError(errorString, logString);
                edu.pitt.dbmi.facebase.hd.HumanDataController.reportDbConnectionFailure();
                log.error("Unable to load annotated class for hibernate: " + className, ex);
            }

            hibernateConf.setProperty("hibernate.connection.driver_class", "com.mysql.jdbc.Driver")
                    .setProperty("hibernate.connection.url", connectionURL)
                    .setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLDialect")
                    .setProperty("hibernate.connection.username", username)
                    .setProperty("hibernate.connection.password", password)
                    .setProperty("hibernate.show_sql", "false")
                    .setProperty("hibernate.current_session_context_class", "thread")
                    .setProperty("hibernate.connection.provider_class",
                            "org.hibernate.connection.C3P0ConnectionProvider")
                    .setProperty("hibernate.c3p0.acquire_increment", "1")
                    .setProperty("hibernate.c3p0.idle_test_period", "240")
                    .setProperty("hibernate.c3p0.timeout", "600").setProperty("hibernate.c3p0.max_size", "100")
                    .setProperty("hibernate.c3p0.min_size", "3")
                    .setProperty("hibernate.c3p0.validate",
                            "false") /*this is an expensive property to turn on...*/
                    .setProperty("hibernate.c3p0.max_statements", "500")
                    .setProperty("hibernate.cache.use_second_level_cache", "false")
                    .setProperty("hibernate.jdbc.batch.size", "20");

            lclSessionFactory = hibernateConf.buildSessionFactory();

        }

    } catch (Throwable ex) {
        String errorString = "Initial SessionFactory creation failed." + ex.toString();
        String logString = ex.getMessage();
        edu.pitt.dbmi.facebase.hd.HumanDataController.addError(errorString, logString);
        edu.pitt.dbmi.facebase.hd.HumanDataController.reportDbConnectionFailure();
        log.error("Initial SessionFactory creation failed.", ex);
        throw new ExceptionInInitializerError(ex);
    }

    return (lclSessionFactory);
}