Example usage for org.hibernate.cfg Configuration setProperties

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

Introduction

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

Prototype

public Configuration setProperties(Properties properties) 

Source Link

Document

Specify a completely new set of properties

Usage

From source file:OpenRate.customerinterface.webservices.HibernateUtil.java

License:Open Source License

/**
 * Return the current session factory/*from   w w  w. ja v a 2  s .c  om*/
 *
 * @return
 */
private static SessionFactory getSessionFactory(boolean useBeansList) {
    try {
        if (sessionFactory == null) {
            if (useBeansList) {
                // use the J2EE type beans list
                Configuration configuration = new Configuration();

                // load all beans
                InputStream is = HibernateUtil.class.getResourceAsStream("hibernateBeans.lst");
                BufferedReader reader = new BufferedReader(new InputStreamReader(is));
                String line;

                while ((line = reader.readLine()) != null) {
                    configuration.addResource(line);
                }

                Properties properties = new Properties();

                properties.load(HibernateUtil.class.getResourceAsStream("hibernate.properties"));
                configuration.setProperties(properties);
                sessionFactory = configuration.buildSessionFactory();
            } else {
                // Use the plain old session factory
                sessionFactory = new Configuration().configure().buildSessionFactory();
            }
        }
    } catch (Throwable ex) {
        log.error("Initial SessionFactory creation failed.", ex);

        throw new ExceptionInInitializerError(ex);
    }

    return sessionFactory;
}

From source file:org.apache.click.extras.hibernate.SessionContext.java

License:Apache License

/**
 * Initialize the configuration instance.
 * <p/>//w ww  . j  a v a 2  s. com
 * You can override this method and manually setup the configuration:
 * <pre class="prettyprint">
 * public Configuration createConfiguration() {
 *     configuration.setProperties(System.getProperties());
 *     configuration.configure();
 * }</pre>
 *
 * @param configuration the configuration to initialize
 */
public void initConfiguration(Configuration configuration) {
    configuration.setProperties(System.getProperties());
    configuration.configure();
}

From source file:org.apache.ignite.cache.store.hibernate.CacheHibernateBlobStore.java

License:Apache License

/**
 * Initializes store./*from ww w  . ja v  a 2  s  .  c o m*/
 *
 * @throws IgniteException If failed to initialize.
 */
private void init() throws IgniteException {
    if (initGuard.compareAndSet(false, true)) {
        if (log.isDebugEnabled())
            log.debug("Initializing cache store.");

        try {
            if (sesFactory != null)
                // Session factory has been provided - nothing to do.
                return;

            if (!F.isEmpty(hibernateCfgPath)) {
                try {
                    URL url = new URL(hibernateCfgPath);

                    sesFactory = new Configuration().configure(url).buildSessionFactory();

                    if (log.isDebugEnabled())
                        log.debug("Configured session factory using URL: " + url);

                    // Session factory has been successfully initialized.
                    return;
                } catch (MalformedURLException e) {
                    if (log.isDebugEnabled())
                        log.debug("Caught malformed URL exception: " + e.getMessage());
                }

                // Provided path is not a valid URL. File?
                File cfgFile = new File(hibernateCfgPath);

                if (cfgFile.exists()) {
                    sesFactory = new Configuration().configure(cfgFile).buildSessionFactory();

                    if (log.isDebugEnabled())
                        log.debug("Configured session factory using file: " + hibernateCfgPath);

                    // Session factory has been successfully initialized.
                    return;
                }

                // Provided path is not a file. Classpath resource?
                sesFactory = new Configuration().configure(hibernateCfgPath).buildSessionFactory();

                if (log.isDebugEnabled())
                    log.debug("Configured session factory using classpath resource: " + hibernateCfgPath);
            } else {
                if (hibernateProps == null) {
                    U.warn(log, "No Hibernate configuration has been provided for store (will use default).");

                    hibernateProps = new Properties();

                    hibernateProps.setProperty("hibernate.connection.url", DFLT_CONN_URL);
                    hibernateProps.setProperty("hibernate.show_sql", DFLT_SHOW_SQL);
                    hibernateProps.setProperty("hibernate.hbm2ddl.auto", DFLT_HBM2DDL_AUTO);
                }

                Configuration cfg = new Configuration();

                cfg.setProperties(hibernateProps);

                assert resourceAvailable(MAPPING_RESOURCE) : MAPPING_RESOURCE;

                cfg.addResource(MAPPING_RESOURCE);

                sesFactory = cfg.buildSessionFactory();

                if (log.isDebugEnabled())
                    log.debug("Configured session factory using properties: " + hibernateProps);
            }
        } catch (HibernateException e) {
            throw new IgniteException("Failed to initialize store.", e);
        } finally {
            initLatch.countDown();
        }
    } else if (initLatch.getCount() > 0) {
        try {
            U.await(initLatch);
        } catch (IgniteInterruptedCheckedException e) {
            throw new IgniteException(e);
        }
    }

    if (sesFactory == null)
        throw new IgniteException("Cache store was not properly initialized.");
}

From source file:org.archiviststoolkit.hibernate.SessionFactory.java

License:Open Source License

/**
 * As this is a singleton the constructor is private.
 * In here we initialise and configure the hibernate session factory
 * making sure that it happens only once
 *//*from ww  w.  jav a  2s. co m*/

private SessionFactory() {

    try {
        Configuration config = new Configuration().configure();
        Properties properties = config.getProperties();
        properties.setProperty("hibernate.connection.driver_class", driverClass);
        if (SessionFactory.databaseType.equals(DATABASE_TYPE_MYSQL)) {
            properties.setProperty("hibernate.connection.url",
                    getDatabaseUrl() + "?useUnicode=yes&characterEncoding=utf8");
        } else {
            properties.setProperty("hibernate.connection.url", getDatabaseUrl());
        }

        //deal with oracle specific settings
        if (SessionFactory.databaseType.equals(DATABASE_TYPE_ORACLE)) {
            properties.setProperty("hibernate.jdbc.batch_size", "0");
            properties.setProperty("hibernate.jdbc.use_streams_for_binary", "true");
            properties.setProperty("SetBigStringTryClob", "true");
        }
        properties.setProperty("hibernate.connection.username", getUserName());
        properties.setProperty("hibernate.connection.password", getPassword());
        properties.setProperty("hibernate.dialect", getHibernateDialect());
        if (SessionFactory.updateStructure) {
            properties.setProperty("hibernate.hbm2ddl.auto", "update");
        }
        config.setProperties(properties);
        sessionFactory = config.buildSessionFactory();
        //test the session factory to make sure it is working
    } catch (Exception hibernateException) {
        logger.log(Level.SEVERE, "Failed to startup hibernate engine", hibernateException);
        throw new RuntimeException(hibernateException);
        //            ErrorDialog dialog = new ErrorDialog("There is a problem initializing hibernate.",
        //                    StringHelper.getStackTrace(hibernateException));
        //            dialog.showDialog();
        //            System.exit(1);
    }
}

From source file:org.archiviststoolkit.plugin.dbdialog.RemoteDBConnectDialog.java

/**
 * Connect to the AT database at the given location. This does not check database version
 * so the it should be able to work with version 1.5 and 1.5.7
 *///from   w w  w  .  j av  a  2  s  . co  m
private boolean connectToDatabase2() {
    // based on the database type set the driver and hibernate dialect
    String databaseType = (String) comboBox2.getSelectedItem();
    String driverClass = "";
    String hibernateDialect = "";

    if (databaseType.equals(SessionFactory.DATABASE_TYPE_MYSQL)) {
        driverClass = "com.mysql.jdbc.Driver";
        hibernateDialect = "org.hibernate.dialect.MySQLInnoDBDialect";
    } else if (databaseType.equals(SessionFactory.DATABASE_TYPE_MICROSOFT_SQL_SERVER)) {
        driverClass = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
        hibernateDialect = "org.hibernate.dialect.SQLServerDialect";
    } else if (databaseType.equals(SessionFactory.DATABASE_TYPE_ORACLE)) {
        driverClass = "oracle.jdbc.OracleDriver";
        hibernateDialect = "org.hibernate.dialect.Oracle10gDialect";
    } else if (databaseType.equals(SessionFactory.DATABASE_TYPE_INTERNAL)) {
        driverClass = "org.hsqldb.jdbcDriver";
        hibernateDialect = "org.hibernate.dialect.HSQLDialect";
    } else { // should never get here
        System.out.println("Unknown database type : " + databaseType);
        return false;
    }

    // now attempt to build the session factory
    String databaseUrl = (String) connectionUrl.getSelectedItem();
    String userName = textField1.getText();
    String password = new String(passwordField1.getPassword());

    try {
        Configuration config = new Configuration().configure();
        Properties properties = config.getProperties();
        properties.setProperty("hibernate.connection.driver_class", driverClass);
        if (databaseType.equals(SessionFactory.DATABASE_TYPE_MYSQL)) {
            properties.setProperty("hibernate.connection.url",
                    databaseUrl + "?useUnicode=yes&characterEncoding=utf8");
        } else {
            properties.setProperty("hibernate.connection.url", databaseUrl);
        }
        //deal with oracle specific settings
        if (databaseType.equals(SessionFactory.DATABASE_TYPE_ORACLE)) {
            properties.setProperty("hibernate.jdbc.batch_size", "0");
            properties.setProperty("hibernate.jdbc.use_streams_for_binary", "true");
            properties.setProperty("SetBigStringTryClob", "true");
        }
        properties.setProperty("hibernate.connection.username", userName);
        properties.setProperty("hibernate.connection.password", password);
        properties.setProperty("hibernate.dialect", hibernateDialect);
        config.setProperties(properties);
        sessionFactory = config.buildSessionFactory();

        //test the session factory to make sure it is working
        testHibernate();

        return true; // connected successfully so return true
    } catch (Exception hibernateException) {
        hibernateException.printStackTrace();

        JOptionPane.showMessageDialog(this, "Failed to start hibernate engine ...", "Hibernate Error",
                JOptionPane.ERROR_MESSAGE);

        return false;
    }
}

From source file:org.archiviststoolkit.plugin.dbdialog.RemoteDBConnectDialogLight.java

/**
 * Connect to the AT database at the given location. This does not check database version
 * so the it should be able to work with version 1.5 and 1.5.7
 *//*ww w  .ja v a 2s.c  o  m*/
private boolean connectToDatabase2() {
    // based on the database type set the driver and hibernate dialect
    String databaseType = (String) comboBox2.getSelectedItem();
    String driverClass = "";
    String hibernateDialect = "";

    if (databaseType.equals(SessionFactory.DATABASE_TYPE_MYSQL)) {
        driverClass = "com.mysql.jdbc.Driver";
        hibernateDialect = "org.hibernate.dialect.MySQLInnoDBDialect";
    } else if (databaseType.equals(SessionFactory.DATABASE_TYPE_MICROSOFT_SQL_SERVER)) {
        driverClass = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
        hibernateDialect = "org.hibernate.dialect.SQLServerDialect";
    } else if (databaseType.equals(SessionFactory.DATABASE_TYPE_ORACLE)) {
        driverClass = "oracle.jdbc.OracleDriver";
        hibernateDialect = "org.hibernate.dialect.Oracle10gDialect";
    } else if (databaseType.equals(SessionFactory.DATABASE_TYPE_INTERNAL)) {
        driverClass = "org.hsqldb.jdbcDriver";
        hibernateDialect = "org.hibernate.dialect.HSQLDialect";
    } else { // should never get here
        System.out.println("Unknown database type : " + databaseType);
        return false;
    }

    // now attempt to build the session factory
    String databaseUrl = (String) connectionUrl.getSelectedItem();
    String userName = textField1.getText();
    String password = new String(passwordField1.getPassword());

    try {
        connectionMessage = "Connecting to: " + databaseUrl;
        System.out.println(connectionMessage);

        Configuration config = new Configuration().configure();
        Properties properties = config.getProperties();
        properties.setProperty("hibernate.connection.driver_class", driverClass);
        if (databaseType.equals(SessionFactory.DATABASE_TYPE_MYSQL)) {
            properties.setProperty("hibernate.connection.url",
                    databaseUrl + "?useUnicode=yes&characterEncoding=utf8");
        } else {
            properties.setProperty("hibernate.connection.url", databaseUrl);
        }
        //deal with oracle specific settings
        if (databaseType.equals(SessionFactory.DATABASE_TYPE_ORACLE)) {
            properties.setProperty("hibernate.jdbc.batch_size", "0");
            properties.setProperty("hibernate.jdbc.use_streams_for_binary", "true");
            properties.setProperty("SetBigStringTryClob", "true");
        }
        properties.setProperty("hibernate.connection.username", userName);
        properties.setProperty("hibernate.connection.password", password);
        properties.setProperty("hibernate.dialect", hibernateDialect);
        config.setProperties(properties);
        sessionFactory = config.buildSessionFactory();

        //test the session factory to make sure it is working
        testHibernate();

        session = sessionFactory.openSession();

        connectionMessage += "\nSuccess ...\n\n";
        System.out.println("Success ...");

        return true; // connected successfully so return true
    } catch (Exception hibernateException) {
        hibernateException.printStackTrace();

        JOptionPane.showMessageDialog(this, "Failed to start hibernate engine ...", "Hibernate Error",
                JOptionPane.ERROR_MESSAGE);

        return false;
    }
}

From source file:org.bonitasoft.engine.business.data.impl.SchemaManager.java

License:Open Source License

private Configuration buildConfiguration(final Set<String> managedClasses) {
    final Configuration cfg = new Configuration();
    final Properties properties = new Properties();
    properties.putAll(configuration);//w w w.jav a 2s. com
    for (final String entity : managedClasses) {
        cfg.addAnnotatedClass(getMappedClass(entity));
    }
    cfg.setProperties(properties);
    return cfg;
}

From source file:org.codehaus.griffon.runtime.hibernate3.internal.HibernateConfigurationHelper.java

License:Apache License

private void applyProperties(Configuration config) {
    Object props = getConfigValue(sessionConfig, PROPS, null);
    if (props instanceof Properties) {
        config.setProperties((Properties) props);
    } else if (props instanceof Map) {
        for (Map.Entry<String, String> entry : ((Map<String, String>) props).entrySet()) {
            config.setProperty(entry.getKey(), entry.getValue());
        }/*from  w  w  w  .  ja v  a 2  s .c om*/
    }

    if (getConfigValueAsBoolean(sessionConfig, "logSql", false)) {
        config.setProperty("hibernate.show_sql", "true");
    }
    if (getConfigValueAsBoolean(sessionConfig, "formatSql", false)) {
        config.setProperty("hibernate.format_sql", "true");
    }
}

From source file:org.codehaus.griffon.runtime.hibernate5.internal.HibernateConfigurationHelper.java

License:Apache License

private void applyProperties(Configuration config) {
    Object props = getConfigValue(sessionConfig, PROPS, null);
    if (props instanceof Properties) {
        config.setProperties((Properties) props);
    } else if (props instanceof Map) {
        for (Map.Entry<String, String> entry : ((Map<String, String>) props).entrySet()) {
            config.setProperty(entry.getKey(), entry.getValue());
        }//from w  w w. ja v a2 s .co  m
    }

    if (getConfigValueAsBoolean(sessionConfig, "logSql", false)) {
        config.setProperty("hibernate.show_sql", "true");
    }
    if (getConfigValueAsBoolean(sessionConfig, "formatSql", false)) {
        config.setProperty("hibernate.format_sql", "true");
    }

}

From source file:org.codehaus.mojo.appfuse.utility.ConfigurationUtility.java

License:Apache License

/**
 * This method will run some basic preparation and procssing tasks on the configuration such as loading properties
 * files from the file system into a properties object, loading naming strategy classes and entity resolver classes.
 * // w  w  w .ja  va  2  s .co  m
 * @param inConfiguration
 *            The configuration to configure.
 * 
 * @throws MojoExecutionException
 *             Thrown if the configuration properties cannot be loaded.
 */
protected void doConfiguration(final Configuration inConfiguration) throws MojoExecutionException {
    validateParameters();

    if (propertyFile != null) {
        Properties properties = new Properties();

        try {
            properties.load(new FileInputStream(propertyFile));
        } catch (FileNotFoundException ex) {
            throw new MojoExecutionException(propertyFile + " not found.", ex);
        } catch (IOException ex) {
            throw new MojoExecutionException("Problem while loading " + propertyFile, ex);
        }

        inConfiguration.setProperties(properties);
    }

    if (entityResolver != null) {

        try {
            Class resolver = ReflectHelper.classForName(entityResolver, this.getClass());
            Object object = resolver.newInstance();
            inConfiguration.setEntityResolver((EntityResolver) object);

            if (LOG.isDebugEnabled()) {
                LOG.debug("Using " + entityResolver + " as entity resolver");
            }
        } catch (Exception e) {
            throw new MojoExecutionException(
                    "Could not create or find " + entityResolver + " class to use for entity resolvement");
        }
    }

    if (namingStrategy != null) {

        try {
            Class resolver = ReflectHelper.classForName(namingStrategy, this.getClass());
            Object object = resolver.newInstance();
            inConfiguration.setNamingStrategy((NamingStrategy) object);

            if (LOG.isDebugEnabled()) {
                LOG.debug("Using " + namingStrategy + " as naming strategy");
            }
        } catch (Exception e) {
            throw new MojoExecutionException(
                    "Could not create or find " + namingStrategy + " class to use for naming strategy");
        }
    }

    if (configurationFile != null) {
        inConfiguration.configure(configurationFile);
    }

    addMappings(getFiles());
}