Example usage for org.hibernate.boot.registry StandardServiceRegistryBuilder StandardServiceRegistryBuilder

List of usage examples for org.hibernate.boot.registry StandardServiceRegistryBuilder StandardServiceRegistryBuilder

Introduction

In this page you can find the example usage for org.hibernate.boot.registry StandardServiceRegistryBuilder StandardServiceRegistryBuilder.

Prototype

public StandardServiceRegistryBuilder() 

Source Link

Document

Create a default builder.

Usage

From source file:org.qbi.seriescalendar.web.utils.HibernateUtil.java

private static SessionFactory buildSessionFactory() {
    try {/*from  www.  j  a va2  s.c  om*/
        // Create the SessionFactory from hibernate.cfg.xml
        Configuration configuration = new Configuration();
        configuration.configure("hibernate.cfg.xml");
        System.out.println("Hibernate Configuration loaded");

        //apply configuration property settings to StandardServiceRegistryBuilder
        ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
                .applySettings(configuration.getProperties()).build();
        System.out.println("Hibernate serviceRegistry created");

        return configuration.buildSessionFactory(serviceRegistry);
    } catch (Throwable ex) {
        // Make sure you log the exception, as it might be swallowed
        System.err.println("Initial SessionFactory creation failed." + ex);
        throw new ExceptionInInitializerError(ex);
    }
}

From source file:org.semtix.db.hibernate.HibernateUtil.java

License:Open Source License

private static SessionFactory buildSessionFactory() {

    Configuration configuration;//from  w ww  . j a  v a2  s  . c o m
    try {

        String path = SettingsExternal.HIBERNATE_CONF_XML;

        if (path.trim().length() <= 1) {
            configuration = new Configuration().configure();
        } else {
            // Create the SessionFactory from hibernate.cfg.xml
            configuration = new Configuration().configure(new File(path));
        }

    } catch (Throwable ex) {
        // Make sure you log the exception, as it might be swallowed
        configuration = new Configuration().configure();
    }

    StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder()
            .applySettings(configuration.getProperties());

    return configuration.buildSessionFactory(builder.build());
}

From source file:org.specrunner.hibernate4.PluginSessionFactory.java

License:Open Source License

/**
 * Create session service registry./* ww  w. jav  a  2s  .  com*/
 * 
 * @param cfg
 *            A configuration.
 * @return A service registry.
 */
protected ServiceRegistry createServiceRegistry(Configuration cfg) {
    Properties properties = cfg.getProperties();
    Environment.verifyProperties(properties);
    ConfigurationHelper.resolvePlaceHolders(properties);
    ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(properties).build();
    return serviceRegistry;
}

From source file:org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategyTests.java

License:Apache License

private StandardServiceRegistry createServiceRegistry() {
    return new StandardServiceRegistryBuilder().applySetting(AvailableSettings.DIALECT, H2Dialect.class)
            .build();/*from   ww  w. j  ava 2  s  . c o m*/
}

From source file:org.springframework.cloud.dataflow.server.repository.SchemaGenerationTests.java

License:Apache License

private void generateDdlFiles(String dialect, File tempDir, PersistenceUnitInfo persistenceUnitInfo) {
    logger.info("Generating DDL script for " + dialect);

    final MetadataSources metadata = new MetadataSources(new StandardServiceRegistryBuilder()
            .applySetting("hibernate.dialect", "org.hibernate.dialect." + dialect + "Dialect")
            .applySetting("hibernate.physical_naming_strategy", SpringPhysicalNamingStrategy.class.getName())
            .applySetting("hibernate.implicit_naming_strategy", SpringImplicitNamingStrategy.class.getName())
            .build());/* w ww . j  a  v  a 2s .  c  o m*/

    for (String clazz : persistenceUnitInfo.getManagedClassNames()) {
        logger.info(clazz);
        metadata.addAnnotatedClassName(clazz);
    }

    final SchemaExport export;
    try {
        export = new SchemaExport();
        export.setDelimiter(";");
        export.setFormat(true);
        export.setOutputFile(new File(tempDir, "schema-" + dialect.toLowerCase() + ".sql").getAbsolutePath());
    } catch (HibernateException e) {
        throw new IllegalStateException(e);
    }
    EnumSet<TargetType> targetTypes = EnumSet.of(TargetType.SCRIPT);
    export.execute(targetTypes, SchemaExport.Action.BOTH, metadata.buildMetadata());
}

From source file:org.thelq.stackexchange.dbimport.DatabaseWriter.java

License:Apache License

public static void buildSessionFactory(DumpContainer container) throws HibernateException {
    container.setHibernateConfiguration(new Configuration());
    container.getHibernateConfiguration().configure();
    container.getHibernateConfiguration().setProperty("hibernate.connection.username", username);
    container.getHibernateConfiguration().setProperty("hibernate.connection.password", password);
    container.getHibernateConfiguration().setProperty("hibernate.connection.url", jdbcString);
    container.getHibernateConfiguration().setProperty("hibernate.connection.driver_class", driver);
    container.getHibernateConfiguration().setProperty("hibernate.dialect", dialect);
    container.getHibernateConfiguration().setProperty("hibernate.jdbc.batch_size", Integer.toString(batchSize));
    container.getHibernateConfiguration().setNamingStrategy(new PrefixNamingStrategy(
            StringUtils.defaultString(globalPrefix) + StringUtils.defaultString(container.getTablePrefix())));
    container.setServiceRegistry(new StandardServiceRegistryBuilder()
            .applySettings(container.getHibernateConfiguration().getProperties()).build());
    container.setSessionFactory(/*w  w  w  .ja  v a  2s .co m*/
            container.getHibernateConfiguration().buildSessionFactory(container.getServiceRegistry()));

    //Make a test connection so we know if this actually works
    Session testSession = container.getSessionFactory().openSession();
    testSession.beginTransaction();
    testSession.close();
    log.info("Database ready for " + Utils.getLongLocation(container));
}

From source file:org.transitime.db.hibernate.HibernateUtils.java

License:Open Source License

/**
 * Creates a new session factory. This is to be cached and only access
 * internally since creating one is expensive.
 * /*from  ww  w.ja v  a  2 s.  co  m*/
 * @param dbName
 * @return
 */
private static SessionFactory createSessionFactory(String dbName) throws HibernateException {
    logger.debug("Creating new Hibernate SessionFactory for dbName={}", dbName);

    // Create a Hibernate configuration based on customized config file
    Configuration config = new Configuration();

    // Want to be able to specify a configuration file for now
    // since developing in Eclipse and want all config files
    // to be in same place. But the Config.configure(String) 
    // method can't seem to work with a Windows directory name such
    // as C:/users/Mike/software/hibernate.cfg.xml . Therefore create
    // a File object for that file name and pass in the File object
    // to configure().
    String fileName = DbSetupConfig.getHibernateConfigFileName();
    logger.info("Configuring Hibernate for dbName={} using config file={}", dbName, fileName);
    File f = new File(fileName);
    if (!f.exists()) {
        logger.info(
                "The Hibernate file {} doesn't exist as a regular file " + "so seeing if it is in classpath.",
                fileName);

        // Couldn't find file directly so look in classpath for it
        ClassLoader classLoader = HibernateUtils.class.getClassLoader();
        URL url = classLoader.getResource(fileName);
        if (url != null)
            f = new File(url.getFile());
    }
    if (f.exists())
        config.configure(f);
    else {
        logger.error("Could not load in hibernate config file {}", fileName);
    }

    // Add the annotated classes so that they can be used
    AnnotatedClassesList.addAnnotatedClasses(config);

    // Set the db info for the URL, user name, and password. Use values 
    // from CoreConfig if set. If they are not set then the values will be 
    // obtained from the hibernate.cfg.xml 
    // config file.
    String dbUrl = null;
    if (DbSetupConfig.getDbHost() != null) {
        dbUrl = "jdbc:" + DbSetupConfig.getDbType() + "://" + DbSetupConfig.getDbHost() + "/" + dbName;
        config.setProperty("hibernate.connection.url", dbUrl);
    } else {
        dbUrl = config.getProperty("hibernate.connection.url");
    }

    String dbUserName = DbSetupConfig.getDbUserName();
    if (dbUserName != null) {
        config.setProperty("hibernate.connection.username", dbUserName);
    } else {
        dbUserName = config.getProperty("hibernate.connection.username");
    }

    if (DbSetupConfig.getDbPassword() != null)
        config.setProperty("hibernate.connection.password", DbSetupConfig.getDbPassword());

    // Log info, but don't log password. This can just be debug logging
    // even though it is important because the C3P0 connector logs the info.
    logger.debug(
            "For Hibernate factory project dbName={} " + "using url={} username={}, and configured password",
            dbName, dbUrl, dbUserName);

    // Get the session factory for persistence
    Properties properties = config.getProperties();
    ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(properties).build();
    SessionFactory sessionFactory = config.buildSessionFactory(serviceRegistry);

    // Return the factory
    return sessionFactory;
}

From source file:org.vibur.dbcp.util.HibernateTestUtils.java

License:Apache License

private static SessionFactory buildSessionFactory(String configFileName) {
    try {/*w w w .  j  a  v  a2s  . c  o  m*/
        Configuration cfg = new Configuration().configure(configFileName);
        cfg.addAnnotatedClass(Actor.class);
        ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
                .applySettings(cfg.getProperties()).build();
        return cfg.buildSessionFactory(serviceRegistry);
    } catch (HibernateException e) {
        throw new ExceptionInInitializerError(e);
    }
}

From source file:org.wattdepot.server.depository.impl.hibernate.Manager.java

License:Open Source License

/**
 * @param properties The ServerProperties that contain the database
 *        configuration.// ww w.j a v  a  2  s  .  co  m
 * @return The singleton SessionFactory.
 */
public static SessionFactory getFactory(ServerProperties properties) {
    if (sessionFactory == null) {
        Configuration cfg = new Configuration()
                .addAnnotatedClass(
                        org.wattdepot.server.depository.impl.hibernate.CollectorProcessDefinitionImpl.class)
                .addAnnotatedClass(org.wattdepot.server.depository.impl.hibernate.DepositoryImpl.class)
                .addAnnotatedClass(
                        org.wattdepot.server.depository.impl.hibernate.DepositorySensorContribution.class)
                .addAnnotatedClass(
                        org.wattdepot.server.depository.impl.hibernate.MeasurementPruningDefinitionImpl.class)
                .addAnnotatedClass(org.wattdepot.server.depository.impl.hibernate.MeasurementImpl.class)
                .addAnnotatedClass(org.wattdepot.server.depository.impl.hibernate.MeasurementTypeImpl.class)
                .addAnnotatedClass(org.wattdepot.server.depository.impl.hibernate.PropertyImpl.class)
                .addAnnotatedClass(org.wattdepot.server.depository.impl.hibernate.RowCount.class)
                .addAnnotatedClass(org.wattdepot.server.depository.impl.hibernate.SensorImpl.class)
                .addAnnotatedClass(org.wattdepot.server.depository.impl.hibernate.SensorGroupImpl.class)
                .addAnnotatedClass(org.wattdepot.server.depository.impl.hibernate.SensorModelImpl.class)
                .addAnnotatedClass(org.wattdepot.server.depository.impl.hibernate.OrganizationImpl.class)
                .addAnnotatedClass(org.wattdepot.server.depository.impl.hibernate.UserInfoImpl.class)
                .addAnnotatedClass(org.wattdepot.server.depository.impl.hibernate.UserPasswordImpl.class)
                .setProperty("hibernate.connection.driver_class",
                        properties.get(ServerProperties.DB_CONNECTION_DRIVER))
                .setProperty("hibernate.connection.url", properties.get(ServerProperties.DB_CONNECTION_URL))
                .setProperty("hibernate.connection.username", properties.get(ServerProperties.DB_USER_NAME))
                .setProperty("hibernate.connection.password", properties.get(ServerProperties.DB_PASSWORD))
                .setProperty("hibernate.c3p0.min_size", "5").setProperty("hibernate.c3p0.max_size", "20")
                .setProperty("hibernate.c3p0.timeout", "1800")
                .setProperty("hibernate.c3p0.max_statements", "50")
                .setProperty("hibernate.dialect", "org.hibernate.dialect.PostgreSQLDialect")
                .setProperty("hibernate.show_sql", properties.get(ServerProperties.DB_SHOW_SQL))
                .setProperty("hibernate.hbm2ddl.auto", properties.get(ServerProperties.DB_TABLE_UPDATE));
        serviceRegistry = new StandardServiceRegistryBuilder().applySettings(cfg.getProperties()).build();
        // A SessionFactory is set up once for an application
        sessionFactory = cfg.buildSessionFactory(serviceRegistry);

        // // A SessionFactory is set up once for an application
        //       sessionFactory = new Configuration().configure() // configures settings
        //       // from
        //       // hibernate.cfg.xml
        //       .buildSessionFactory();

    }
    return sessionFactory;
}

From source file:org.wattdepot.server.depository.impl.hibernate.Manager.java

License:Open Source License

/**
 * @param properties The ServerProperties that contain the database
 *        configuration.//from   www.  j  a  v  a  2  s.co m
 * @return The singleton SessionFactory.
 */
public static SessionFactory getValidateFactory(ServerProperties properties) {
    if (validateFactory == null) {
        Configuration cfg = new Configuration()
                .addAnnotatedClass(
                        org.wattdepot.server.depository.impl.hibernate.CollectorProcessDefinitionImpl.class)
                .addAnnotatedClass(org.wattdepot.server.depository.impl.hibernate.DepositoryImpl.class)
                .addAnnotatedClass(org.wattdepot.server.depository.impl.hibernate.MeasurementImpl.class)
                .addAnnotatedClass(org.wattdepot.server.depository.impl.hibernate.MeasurementTypeImpl.class)
                .addAnnotatedClass(org.wattdepot.server.depository.impl.hibernate.PropertyImpl.class)
                .addAnnotatedClass(org.wattdepot.server.depository.impl.hibernate.SensorImpl.class)
                .addAnnotatedClass(org.wattdepot.server.depository.impl.hibernate.SensorGroupImpl.class)
                .addAnnotatedClass(org.wattdepot.server.depository.impl.hibernate.SensorModelImpl.class)
                .addAnnotatedClass(org.wattdepot.server.depository.impl.hibernate.OrganizationImpl.class)
                .addAnnotatedClass(org.wattdepot.server.depository.impl.hibernate.UserInfoImpl.class)
                .addAnnotatedClass(org.wattdepot.server.depository.impl.hibernate.UserPasswordImpl.class)
                .setProperty("hibernate.connection.driver_class",
                        properties.get(ServerProperties.DB_CONNECTION_DRIVER))
                .setProperty("hibernate.connection.url", properties.get(ServerProperties.DB_CONNECTION_URL))
                .setProperty("hibernate.connection.username", properties.get(ServerProperties.DB_USER_NAME))
                .setProperty("hibernate.connection.password", properties.get(ServerProperties.DB_PASSWORD))
                .setProperty("hibernate.c3p0.min_size", "5").setProperty("hibernate.c3p0.max_size", "20")
                .setProperty("hibernate.c3p0.timeout", "1800")
                .setProperty("hibernate.c3p0.max_statements", "50")
                .setProperty("hibernate.dialect", "org.hibernate.dialect.PostgreSQLDialect")
                .setProperty("hibernate.show_sql", properties.get(ServerProperties.DB_SHOW_SQL))
                .setProperty("hibernate.hbm2ddl.auto", "validate");
        validateRegistry = new StandardServiceRegistryBuilder().applySettings(cfg.getProperties()).build();
        // A SessionFactory is set up once for an application
        validateFactory = cfg.buildSessionFactory(validateRegistry);

    }
    return validateFactory;
}