Example usage for org.hibernate.cfg Configuration setProperty

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

Introduction

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

Prototype

public Configuration setProperty(String propertyName, String value) 

Source Link

Document

Set a property value by name

Usage

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 www  . ja va2s . c o  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.web4thejob.module.JobletInstallerImpl.java

License:Open Source License

@Override
@SuppressWarnings("unchecked")
public <E extends Exception> List<E> install(List<Joblet> joblets) {
    List<E> exceptions = new ArrayList<E>();

    try {/*from   w  w  w  .  ja  va2s  .co m*/

        final Configuration configuration = new Configuration();
        configuration.setProperty(AvailableSettings.DIALECT,
                connInfo.getProperty(DatasourceProperties.DIALECT));
        configuration.setProperty(AvailableSettings.DRIVER, connInfo.getProperty(DatasourceProperties.DRIVER));
        configuration.setProperty(AvailableSettings.URL, connInfo.getProperty(DatasourceProperties.URL));
        configuration.setProperty(AvailableSettings.USER, connInfo.getProperty(DatasourceProperties.USER));
        configuration.setProperty(AvailableSettings.PASS, connInfo.getProperty(DatasourceProperties.PASSWORD));

        final ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
                .applySettings(configuration.getProperties()).build();

        if (StringUtils.hasText(connInfo.getProperty(DatasourceProperties.SCHEMA_SYNTAX))) {
            String schemaSyntax = connInfo.getProperty(DatasourceProperties.SCHEMA_SYNTAX);
            Connection connection = serviceRegistry.getService(ConnectionProvider.class).getConnection();

            for (Joblet joblet : joblets) {
                for (String schema : joblet.getSchemas()) {
                    Statement statement = connection.createStatement();
                    statement.executeUpdate(schemaSyntax.replace("%s", schema));
                    statement.close();
                }
            }

            if (!connection.getAutoCommit()) {
                connection.commit();
            }
        }

        for (Joblet joblet : joblets) {
            for (Resource resource : joblet.getResources()) {
                configuration.addInputStream(resource.getInputStream());
            }
        }

        SchemaExport schemaExport = new SchemaExport(serviceRegistry, configuration);
        schemaExport.execute(Target.EXPORT, SchemaExport.Type.CREATE);
        exceptions.addAll(schemaExport.getExceptions());

    } catch (Exception e) {
        exceptions.add((E) e);
    }

    return exceptions;

}

From source file:org.web4thejob.orm.CreateSchemaTest.java

License:Open Source License

@Test
public void schemaExportTest() throws IOException, SQLException {

    Log4jConfigurer.initLogging("classpath:org/web4thejob/conf/log4j.xml");

    Properties datasource = new Properties();
    datasource.load(new ClassPathResource(DatasourceProperties.PATH).getInputStream());

    final Configuration configuration = new Configuration();
    configuration.setProperty(AvailableSettings.DIALECT, datasource.getProperty(DatasourceProperties.DIALECT));
    configuration.setProperty(AvailableSettings.DRIVER, datasource.getProperty(DatasourceProperties.DRIVER));
    configuration.setProperty(AvailableSettings.URL, "jdbc:hsqldb:mem:mydb");
    configuration.setProperty(AvailableSettings.USER, datasource.getProperty(DatasourceProperties.USER));
    configuration.setProperty(AvailableSettings.PASS, datasource.getProperty(DatasourceProperties.PASSWORD));

    final ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
            .applySettings(configuration.getProperties()).build();

    Connection connection = serviceRegistry.getService(ConnectionProvider.class).getConnection();
    Statement statement = connection.createStatement();
    statement.executeUpdate("CREATE SCHEMA w4tj;");
    statement.close();//from  www .  ja v a 2s  .c  o m

    PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
    try {
        for (Resource resource : resolver.getResources("classpath*:org/web4thejob/orm/**/*.hbm.xml")) {

            if (resource.getFile().getName().equals("AuxiliaryDatabaseObjects.hbm.xml"))
                continue;

            configuration.addFile(resource.getFile());
        }
    } catch (IOException e) {
        e.printStackTrace();
        throw new RuntimeException(e);
    }

    SchemaExport schemaExport = new SchemaExport(serviceRegistry, configuration);
    schemaExport.execute(Target.EXPORT, SchemaExport.Type.CREATE);

    if (!schemaExport.getExceptions().isEmpty()) {
        throw new RuntimeException((Throwable) schemaExport.getExceptions().get(0));
    }

}

From source file:org.wildfly.extras.db_bootstrap.DbBootstrapScanDetectorProcessor.java

License:Apache License

/**
 * Loads all <code>dbbootstrap.[user-space-cfg-name-here].[hibernate-property-name-here]</code> properties from system
 * properties. <br>/*from w w w .  j  a v  a2  s  .  c  o m*/
 * <br>
 * Any existing hibernate properties with the same name (<code>[hibernate-property-name-here]</code> in above example) will
 * be replaced by the matching system property. <br>
 * <br>
 *
 * @param bootstrapDatabaseAnnotation - bootstrap configuration source
 * @param configuration - the runtime hibernate configuration object
 */
private void configureSettingsFromSystemProperties(BootstrapDatabase bootstrapDatabaseAnnotation,
        Configuration configuration) {
    String propertyPrefix = String.format("%s.%s", DBBOOTSTRAP_SYSTEM_PROPERTY_PREFIX,
            bootstrapDatabaseAnnotation.name());
    DbBootstrapLogger.ROOT_LOGGER.tracef(
            "Searching for system properties with prefix %s to set and/or override hibernate configuration properties",
            propertyPrefix);
    for (Entry<Object, Object> entrySet : (System.getProperties().entrySet())) {
        if (entrySet.getKey().toString().startsWith(propertyPrefix)) {
            String hibernatePropertyName = entrySet.getKey().toString()
                    .replace(String.format("%s.", propertyPrefix), "");
            String oldHibernatePropertyValue = (configuration.getProperty(hibernatePropertyName) == null)
                    ? " (New property)"
                    : String.format(" (Replacing existing property with old value=%s)",
                            configuration.getProperty(hibernatePropertyName));
            String newHibernatePropertyValue = entrySet.getValue().toString();
            DbBootstrapLogger.ROOT_LOGGER.tracef("Setting hibernate property: %s=%s%s", hibernatePropertyName,
                    newHibernatePropertyValue, oldHibernatePropertyValue);
            configuration.setProperty(hibernatePropertyName, newHibernatePropertyValue);
        }
    }
}

From source file:org.wso2.mercury.persistence.hibernate.HibernatePersistenceManager.java

License:Apache License

private void setProperty(Configuration configuration, String parameterName,
        AxisConfiguration axisConfiguration) {
    Parameter parameter = axisConfiguration.getParameter(parameterName);
    if (parameter != null) {
        configuration.setProperty(parameterName, (String) parameter.getValue());
    } else {/*  w  w  w . j a va2s .com*/
        log.warn("Hibernate parameter " + parameterName + " has not been set");
    }
}

From source file:org.wso2.mercury.persistence.hibernate.HibernatePersistenceManagerTest.java

License:Apache License

private Configuration getConfiguration() {

    Configuration configuration = new Configuration();
    configuration.setProperty("hibernate.connection.driver_class", "org.apache.derby.jdbc.EmbeddedDriver");
    configuration.setProperty("hibernate.connection.url", URL_STRING);
    configuration.setProperty("hibernate.connection.username", "mercury");
    configuration.setProperty("hibernate.connection.password", "mercury");
    configuration.setProperty("hibernate.connection.pool_size", "1");
    configuration.setProperty("hibernate.current_session_context_class", "thread");
    configuration.setProperty("hibernate.dialect", "org.hibernate.dialect.DerbyDialect");

    //        configuration.setProperty("hibernate.show_sql","true");
    configuration.setProperty("hibernate.hbm2ddl.auto", "create");
    configuration.addResource("org/wso2/mercury/persistence/hibernate/rm.hbm.xml");

    return configuration;
}

From source file:org.xchain.framework.hibernate.HibernateLifecycle.java

License:Apache License

private static void setXChainDefaults(QName name, Configuration configuration) {
    String dataSourceJndi = configuration.getProperty(Environment.DATASOURCE);
    String connectionProvider = configuration.getProperty(Environment.CONNECTION_PROVIDER);

    if (dataSourceJndi != null && connectionProvider == null) {
        if (log.isInfoEnabled()) {
            log.info("Adding the property '" + Environment.CONNECTION_PROVIDER
                    + "' with value 'org.xchain.framework.hibernate.RebindingDataSourceConnectionProvider' to the hibernate configuration of datasource '"
                    + dataSourceJndi + "'.");
        }//from  w  ww. ja  v a 2s.co  m
        configuration.setProperty(Environment.CONNECTION_PROVIDER,
                "org.xchain.framework.hibernate.RebindingDataSourceConnectionProvider");
    }
}

From source file:org.xwiki.platform.patchservice.storage.PatchStorage.java

License:Open Source License

private void init(XWikiContext context) throws XWikiException {
    System.err.println("storage initializing");
    XWikiHibernateStore storage = ((XWikiHibernateStore) context.getWiki().getNotCacheStore());
    Configuration config = storage.getConfiguration();
    try {/*from   w w  w . j a v  a2  s  .  c  o  m*/
        // Make sure the schema is updated to include the Patch mapping
        config.setProperty("hibernate.hbm2ddl.auto", "update");
        try {
            config.addXML(IOUtils.toString(this.getClass().getResourceAsStream(MAPPING_FILENAME)));
        } catch (DuplicateMappingException e) {
        }
        this.factory = config.buildSessionFactory();
    } catch (MappingException e) {
        throw new XWikiException(XWikiException.MODULE_XWIKI_STORE,
                XWikiException.ERROR_XWIKI_STORE_HIBERNATE_INVALID_MAPPING, "Invalid Patch mapping file", e);
    } catch (HibernateException e) {
        throw new XWikiException(XWikiException.MODULE_XWIKI_STORE, XWikiException.ERROR_XWIKI_UNKNOWN,
                "Unknown error initializing the Patch storage", e);
    } catch (IOException e) {
        throw new XWikiException(XWikiException.MODULE_XWIKI_STORE,
                XWikiException.ERROR_XWIKI_STORE_HIBERNATE_INVALID_MAPPING, "Cannot load Patch mapping file",
                e);
    }
    System.err.println("storage initialized");
}

From source file:org.yestech.maven.HibernateSearchBuildIndexesMojo.java

License:Apache License

public void execute() throws MojoExecutionException {

    if (skip) {//  w w  w .  j a v a2  s  . c  om
        getLog().info("Skipping search index population");
        return;
    }

    Thread thread = Thread.currentThread();
    ClassLoader oldClassLoader = thread.getContextClassLoader();
    thread.setContextClassLoader(getClassLoader());

    FullTextSession fullTextSession = null;
    Connection con = null;
    try {

        Class.forName(driver);
        con = java.sql.DriverManager.getConnection(url, username, password);

        Configuration configuration = new AnnotationConfiguration();
        configuration = configuration.configure(config);
        if (StringUtils.isNotBlank(dialect)) {
            configuration.setProperty("hibernate.dialect", dialect);
        }

        prepareIndexDir(configuration);

        if (StringUtils.isNotBlank(directoryProvider)) {
            configuration.setProperty("hibernate.search.default.directory_provider", directoryProvider);
        }

        fullTextSession = processObjects(fullTextSession, con, configuration);
    } catch (Exception e) {
        throw new MojoExecutionException("Build " + e.getMessage(), e);
    } finally {
        if (fullTextSession != null) {
            fullTextSession.flushToIndexes();
            fullTextSession.flush();
            fullTextSession.close();
        }
        if (con != null) {
            try {
                con.close();
            } catch (SQLException e) {
                getLog().error(e);
            }
        }
        thread.setContextClassLoader(oldClassLoader);
    }

}

From source file:org.yestech.maven.HibernateSearchBuildIndexesMojo.java

License:Apache License

private void prepareIndexDir(Configuration configuration) throws IOException {
    File dir = new File(indexDir);

    if (drop && dir.exists()) {
        getLog().info("Dropping Index Directory: " + indexDir);
        forceDelete(dir);//from  ww  w .  j a va  2 s .c  om
    }

    if (!dir.exists()) {
        getLog().info("Creating Index Directory: " + indexDir);
        //noinspection ResultOfMethodCallIgnored
        dir.mkdirs();
    }
    if (!dir.exists()) {
        throw new IOException("failed to create directory");
    }
    configuration.setProperty("hibernate.search.default.indexBase", indexDir);
}