Example usage for org.hibernate.cfg Configuration getProperties

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

Introduction

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

Prototype

public Properties getProperties() 

Source Link

Document

Get all properties

Usage

From source file:io.dropwizard.sharding.dao.locktest.LockTest.java

License:Apache License

private SessionFactory buildSessionFactory(String dbName) {
    Configuration configuration = new Configuration();
    configuration.setProperty("hibernate.dialect", "org.hibernate.dialect.H2Dialect");
    configuration.setProperty("hibernate.connection.driver_class", "org.h2.Driver");
    configuration.setProperty("hibernate.connection.url", "jdbc:h2:mem:" + dbName);
    configuration.setProperty("hibernate.hbm2ddl.auto", "create");
    configuration.setProperty("hibernate.current_session_context_class", "managed");
    configuration.addAnnotatedClass(SomeLookupObject.class);
    configuration.addAnnotatedClass(SomeOtherObject.class);

    StandardServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
            .applySettings(configuration.getProperties()).build();
    return configuration.buildSessionFactory(serviceRegistry);
}

From source file:io.dropwizard.sharding.dao.RelationalDaoTest.java

License:Apache License

private SessionFactory buildSessionFactory(String dbName) {
    Configuration configuration = new Configuration();
    configuration.setProperty("hibernate.dialect", "org.hibernate.dialect.H2Dialect");
    configuration.setProperty("hibernate.connection.driver_class", "org.h2.Driver");
    configuration.setProperty("hibernate.connection.url", "jdbc:h2:mem:" + dbName);
    configuration.setProperty("hibernate.hbm2ddl.auto", "create");
    configuration.setProperty("hibernate.current_session_context_class", "managed");
    configuration.addAnnotatedClass(RelationalEntity.class);

    StandardServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
            .applySettings(configuration.getProperties()).build();
    return configuration.buildSessionFactory(serviceRegistry);
}

From source file:io.dropwizard.sharding.dao.WrapperDaoTest.java

License:Apache License

private SessionFactory buildSessionFactory(String dbName) {
    Configuration configuration = new Configuration();
    configuration.setProperty("hibernate.dialect", "org.hibernate.dialect.H2Dialect");
    configuration.setProperty("hibernate.connection.driver_class", "org.h2.Driver");
    configuration.setProperty("hibernate.connection.url", "jdbc:h2:mem:" + dbName);
    configuration.setProperty("hibernate.hbm2ddl.auto", "create");
    configuration.setProperty("hibernate.current_session_context_class", "managed");
    configuration.addAnnotatedClass(Order.class);
    configuration.addAnnotatedClass(OrderItem.class);

    StandardServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
            .applySettings(configuration.getProperties()).build();
    return configuration.buildSessionFactory(serviceRegistry);
}

From source file:io.heming.accountbook.facade.FacadeUtil.java

License:Apache License

private static SessionFactory buildSessionFactory() {
    try {/*from w w  w. ja  v a 2 s .  com*/
        // Create the SessionFactory from hibernate.cfg.xml
        Configuration conf = new Configuration();
        conf.configure("hibernate.cfg.xml");
        ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
                .applySettings(conf.getProperties()).build();
        SessionFactory sessionFactory = conf.buildSessionFactory(serviceRegistry);
        return sessionFactory;
    } 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:io.opentracing.contrib.jdbc.HibernateTest.java

License:Apache License

private SessionFactory createSessionFactory(boolean traceWithActiveSpanOnly, List<String> ignored) {
    String ignoredForTrace = TestUtil.buildIgnoredString(ignored);
    Configuration configuration = new Configuration();
    configuration.addAnnotatedClass(Employee.class);
    configuration.setProperty("hibernate.connection.driver_class", "io.opentracing.contrib.jdbc.TracingDriver");
    configuration.setProperty("hibernate.connection.url", "jdbc:tracing:h2:mem:hibernate?" + ignoredForTrace
            + "traceWithActiveSpanOnly=" + traceWithActiveSpanOnly);
    configuration.setProperty("hibernate.connection.username", "sa");
    configuration.setProperty("hibernate.connection.password", "");
    configuration.setProperty("hibernate.dialect", "org.hibernate.dialect.H2Dialect");
    configuration.setProperty("hibernate.hbm2ddl.auto", "create-drop");
    configuration.setProperty("hibernate.show_sql", "true");
    configuration.setProperty("hibernate.connection.pool_size", "10");

    StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder()
            .applySettings(configuration.getProperties());
    return configuration.buildSessionFactory(builder.build());
}

From source file:it.cnr.ilc.lc.hibernatesearchtest.HibernateUtil.java

private static SessionFactory configureSessionFactory() throws HibernateException {
    Configuration configuration = new Configuration();
    configuration.configure();//  ww  w.  j a v  a  2 s .  c o  m

    Properties properties = configuration.getProperties();

    serviceRegistry = new StandardServiceRegistryBuilder().applySettings(properties).build();
    sessionFactory = configuration.buildSessionFactory(serviceRegistry);

    return sessionFactory;
}

From source file:it.doqui.index.ecmengine.business.personalization.multirepository.bootstrap.SchemaBootstrap.java

License:Open Source License

/**
 * Builds the schema from scratch or applies the necessary patches to the schema.
 *//*from  ww  w  .  j  a  v a2 s.  co m*/
private void updateSchema(Configuration cfg, Session session, Connection connection) throws Exception {
    boolean create = false;
    try {
        countAppliedPatches(connection);
    } catch (NoSchemaException e) {
        create = true;
    }
    // Get the dialect
    final Dialect dialect = Dialect.getDialect(cfg.getProperties());
    String dialectStr = dialect.getClass().getName();

    if (create) {
        // the applied patch table is missing - we assume that all other tables are missing
        // perform a full update using Hibernate-generated statements
        File tempFile = TempFileProvider.createTempFile("AlfrescoSchemaCreate-" + dialectStr + "-", ".sql");
        SchemaBootstrap.dumpSchemaCreate(cfg, tempFile);
        executeScriptFile(cfg, connection, tempFile, null);
        // execute post-create scripts (not patches)
        for (String scriptUrl : this.postCreateScriptUrls) {
            executeScriptUrl(cfg, connection, scriptUrl);
        }
    } else {
        // Check for scripts that must have been run
        checkSchemaPatchScripts(cfg, session, connection, validateUpdateScriptPatches, false);
        // Execute any pre-auto-update scripts
        checkSchemaPatchScripts(cfg, session, connection, preUpdateScriptPatches, true);

        // Build and execute changes generated by Hibernate
        File tempFile = null;
        Writer writer = null;
        try {
            DatabaseMetadata metadata = new DatabaseMetadata(connection, dialect);
            String[] sqls = cfg.generateSchemaUpdateScript(dialect, metadata);
            if (sqls.length > 0) {
                tempFile = TempFileProvider.createTempFile("AlfrescoSchemaUpdate-" + dialectStr + "-", ".sql");
                writer = new BufferedWriter(new FileWriter(tempFile));
                for (String sql : sqls) {
                    writer.append(sql);
                    writer.append(";\n");
                }
            }
        } finally {
            if (writer != null) {
                try {
                    writer.close();
                } catch (Throwable e) {
                }
            }
        }
        // execute if there were changes raised by Hibernate
        if (tempFile != null) {
            executeScriptFile(cfg, connection, tempFile, null);
        }

        // Execute any post-auto-update scripts
        checkSchemaPatchScripts(cfg, session, connection, postUpdateScriptPatches, true);
    }
}

From source file:it.doqui.index.ecmengine.business.personalization.multirepository.bootstrap.SchemaBootstrap.java

License:Open Source License

private void executeScriptUrl(Configuration cfg, Connection connection, String scriptUrl) throws Exception {
    Dialect dialect = Dialect.getDialect(cfg.getProperties());
    String dialectStr = dialect.getClass().getName();
    InputStream scriptInputStream = getScriptInputStream(dialect.getClass(), scriptUrl);
    // check that it exists
    if (scriptInputStream == null) {
        throw AlfrescoRuntimeException.create(ERR_SCRIPT_NOT_FOUND, scriptUrl);
    }//from www  .  j av  a2 s  .c o  m
    // write the script to a temp location for future and failure reference
    File tempFile = null;
    try {
        tempFile = TempFileProvider.createTempFile("AlfrescoSchemaUpdate-" + dialectStr + "-", ".sql");
        ContentWriter writer = new FileContentWriter(tempFile);
        writer.putContent(scriptInputStream);
    } finally {
        try {
            scriptInputStream.close();
        } catch (Throwable e) {
        } // usually a duplicate close
    }
    // now execute it
    String dialectScriptUrl = scriptUrl.replaceAll(PLACEHOLDER_SCRIPT_DIALECT, dialect.getClass().getName());
    // Replace the script placeholders
    executeScriptFile(cfg, connection, tempFile, dialectScriptUrl);
}

From source file:it.doqui.index.ecmengine.business.personalization.multirepository.bootstrap.SchemaBootstrap.java

License:Open Source License

private void doBootstrap() {
    // do everything in a transaction
    Session session = getSessionFactory().openSession();
    try {//from  w w w  .j av a 2  s  .  c  om
        // make sure that we AUTO-COMMIT
        Connection connection = session.connection();
        connection.setAutoCommit(true);

        // DoQui workaround: getConfiguration() solleverebbe una IllegalStateException()
        Configuration cfg = localSessionFactory.getConfigurationOverride();

        // Check and dump the dialect being used
        Dialect dialect = Dialect.getDialect(cfg.getProperties());
        Class<?> dialectClazz = dialect.getClass();
        LogUtil.info(logger, "[SchemaBootstrap::doBootstrap] Repository '"
                + RepositoryManager.getCurrentRepository() + "' -- " + MSG_DIALECT_USED,
                dialectClazz.getName());
        if (dialectClazz.equals(MySQLDialect.class) || dialectClazz.equals(MySQL5Dialect.class)) {
            LogUtil.warn(
                    logger, "[SchemaBootstrap::doBootstrap] Repository '"
                            + RepositoryManager.getCurrentRepository() + "' -- " + WARN_DIALECT_UNSUPPORTED,
                    dialectClazz.getName());
        }

        if (dialectClazz.equals(HSQLDialect.class)) {
            logger.info("[SchemaBootstrap::doBootstrap] Repository '" + RepositoryManager.getCurrentRepository()
                    + "' -- " + I18NUtil.getMessage(WARN_DIALECT_HSQL));
        }

        // Ensure that our static connection provider is used
        String defaultConnectionProviderFactoryClass = cfg.getProperty(Environment.CONNECTION_PROVIDER);
        cfg.setProperty(Environment.CONNECTION_PROVIDER, SchemaBootstrapConnectionProvider.class.getName());
        SchemaBootstrapConnectionProvider.setBootstrapConnection(connection);

        // update the schema, if required
        if (updateSchema) {
            // Check and record that the bootstrap has started
            setBootstrapStarted(connection);

            // Allocate buffer for executed statements
            executedStatementsThreadLocal.set(new StringBuilder(1024));

            updateSchema(cfg, session, connection);

            // Copy the executed statements to the output file
            File schemaOutputFile = null;
            if (schemaOuputFilename != null) {
                schemaOutputFile = new File(schemaOuputFilename);
            } else {
                schemaOutputFile = TempFileProvider.createTempFile("AlfrescoSchemaUpdate-All_Statements-",
                        ".sql");
            }
            String executedStatements = executedStatementsThreadLocal.get().toString();
            if (executedStatements.length() == 0) {
                LogUtil.info(logger, "[SchemaBootstrap::doBootstrap] Repository '"
                        + RepositoryManager.getCurrentRepository() + "' -- " + MSG_NO_CHANGES);
            } else {
                FileContentWriter writer = new FileContentWriter(schemaOutputFile);
                writer.setEncoding("UTF-8");
                writer.putContent(executedStatements);
                LogUtil.info(
                        logger, "[SchemaBootstrap::doBootstrap] Repository '"
                                + RepositoryManager.getCurrentRepository() + "' -- " + MSG_ALL_STATEMENTS,
                        schemaOutputFile.getPath());
            }

            // verify that all patches have been applied correctly
            checkSchemaPatchScripts(cfg, session, connection, validateUpdateScriptPatches, false); // check scripts
            checkSchemaPatchScripts(cfg, session, connection, preUpdateScriptPatches, false); // check scripts
            checkSchemaPatchScripts(cfg, session, connection, postUpdateScriptPatches, false); // check scripts

            // Remove the flag indicating a running bootstrap
            setBootstrapCompleted(connection);
        } else {
            LogUtil.info(logger, "[SchemaBootstrap::doBootstrap] Repository '"
                    + RepositoryManager.getCurrentRepository() + "' -- " + MSG_BYPASSING_SCHEMA_UPDATE);
        }

        // Reset the configuration
        cfg.setProperty(Environment.CONNECTION_PROVIDER, defaultConnectionProviderFactoryClass);

        // all done successfully
    } catch (Throwable e) {
        LogUtil.error(logger, e, ERR_UPDATE_FAILED);
        if (updateSchema) {
            throw new AlfrescoRuntimeException(ERR_UPDATE_FAILED, e);
        } else {
            throw new AlfrescoRuntimeException(ERR_VALIDATION_FAILED, e);
        }
    } finally {
        // Remove the connection reference from the threadlocal boostrap
        SchemaBootstrapConnectionProvider.setBootstrapConnection(null);

    }
}

From source file:iu.slam.database.DatabaseHandler.java

License:Open Source License

private DatabaseHandler() {
    Configuration configuration = new Configuration();
    configuration.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
    configuration.setProperty("hibernate.connection.driver_class", "com.mysql.jdbc.Driver");
    configuration.setProperty("hibernate.connection.url",
            "jdbc:mysql://127.0.0.1:3306/slam?autoReconnect=true");//3306 wamp mysql
    configuration.setProperty("hibernate.connection.username", "root");
    configuration.setProperty("hibernate.connection.password", "");
    //configuration.setProperty("hibernate.format_sql", "true");
    //configuration.setProperty("hibernate.show_sql", "true");
    configuration.setProperty("hibernate.connection.provider_class",
            "org.hibernate.service.jdbc.connections.internal.C3P0ConnectionProvider");
    configuration.setProperty("hibernate.c3p0.idleConnectionTestPeriod", "600");
    configuration.setProperty("hibernate.c3p0.testConnectionOnCheckin", "true");

    configuration.addAnnotatedClass(SensorData.class).addAnnotatedClass(Experiment.class)
            .addAnnotatedClass(Photo.class).addAnnotatedClass(Video.class).addAnnotatedClass(PhotoTags.class)
            .addAnnotatedClass(PhotoDrawTag.class);

    sessionFactory = configuration.buildSessionFactory(
            new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry());
    sessionFactory.getStatistics().setStatisticsEnabled(true);

    UtilLog.logDatabase(DatabaseHandler.class, "SessionFactory created");
}