Example usage for org.hibernate.cfg Configuration addProperties

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

Introduction

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

Prototype

public Configuration addProperties(Properties properties) 

Source Link

Document

Add the given properties to ours.

Usage

From source file:org.jbpm.pvm.internal.wire.descriptor.HibernateConfigurationDescriptor.java

License:Open Source License

public void initialize(Object object, WireContext wireContext) {
    Configuration configuration = (Configuration) object;

    apply(cfgOperations, configuration, wireContext);
    apply(cfgCacheOperations, configuration, wireContext);

    if (propertiesDescriptor != null) {
        Properties properties = (Properties) wireContext.create(propertiesDescriptor, false);
        if (log.isDebugEnabled())
            log.debug("adding properties to hibernate configuration: " + properties);
        configuration.addProperties(properties);
    }//  w ww  .j ava 2 s. c o m
}

From source file:org.jpos.ee.support.JPosHibernateConfiguration.java

License:Open Source License

private void configureMappings(Configuration cfg) throws ConfigurationException, IOException {
    try {// w  ww  .  j  a v a2s.  co m
        //Read DB properties.
        String propFile = cfg.getProperty(DB_PROPERTY_FILE);
        propFile = propFile == null ? "cfg/db.properties" : propFile;
        Properties dbProps = loadProperties(propFile);
        if (dbProps != null) {
            cfg.addProperties(dbProps);
        }

        SAXReader reader = new SAXReader();

        List<String> moduleConfigs = ModuleUtils.getModuleEntries("META-INF/org/jpos/ee/modules/");
        for (String moduleConfig : moduleConfigs) {
            final URL url = getClass().getClassLoader().getResource(moduleConfig);
            final Document doc = reader.read(url);
            Element mappings = doc.getRootElement().element("mappings");
            if (mappings != null) {
                addMappings(cfg, mappings, moduleConfig);
            }
        }
    } catch (DocumentException e) {
        throw new ConfigurationException("Could not parse mappings document", e);
    }
}

From source file:org.n52.sos.SQLScriptGenerator.java

License:Open Source License

public static void main(String[] args) {
    try {/* w  w w  . j  a  v a2s. co  m*/
        SQLScriptGenerator sqlScriptGenerator = new SQLScriptGenerator();
        Configuration configuration = new Configuration().configure("/sos-hibernate.cfg.xml");
        int dialectSelection = sqlScriptGenerator.getDialectSelection();
        Dialect dia = sqlScriptGenerator.getDialect(dialectSelection);
        int modelSelection = sqlScriptGenerator.getModelSelection();
        boolean oldConcept = sqlScriptGenerator.isOldConcept(sqlScriptGenerator.getConceptSelection());
        String schema = sqlScriptGenerator.getSchema();
        if (schema != null && !schema.isEmpty()) {
            Properties p = new Properties();
            p.put("hibernate.default_schema", schema);
            configuration.addProperties(p);
        }
        sqlScriptGenerator.setDirectoriesForModelSelection(modelSelection, oldConcept, configuration);
        // create script
        String[] create = configuration.generateSchemaCreationScript(dia);
        List<String> checkedSchema = sqlScriptGenerator.checkSchema(dia, create);
        printToScreen("Scripts are created for: " + dia.toString());
        printToScreen("");
        printToScreen("#######################################");
        printToScreen("##           Create-Script           ##");
        printToScreen("#######################################");
        printToScreen("");
        for (String t : checkedSchema) {
            printToScreen(t + ";");
        }
        // drop script
        String[] drop = configuration.generateDropSchemaScript(dia);
        List<String> checkedDrop = sqlScriptGenerator.checkSchema(dia, drop);
        printToScreen("");
        printToScreen("#######################################");
        printToScreen("##            Drop-Script            ##");
        printToScreen("#######################################");
        printToScreen("");
        for (String t : checkedDrop) {
            printToScreen(t + ";");
        }
        printToScreen("");
        printToScreen("#######################################");
    } catch (IOException ioe) {
        printToScreen("ERROR: IO error trying to read your input!");
        System.exit(1);
    } catch (MissingDriverException mde) {
        System.exit(1);
    } catch (Exception e) {
        printToScreen("ERROR: " + e.getMessage());
        System.exit(1);
    }

}

From source file:org.openeos.hibernate.internal.configurators.FixedConfigurator.java

License:Apache License

@Override
public void init(ConfigurationProvider configurationProvider) {
    LOG.debug("Initializing static fixed configuration");
    Configuration conf = configurationProvider.getConfiguration();
    Properties props = new Properties();
    props.put("hibernate.bytecode.provider", "null");
    props.put("hibernate.current_session_context_class",
            "org.springframework.orm.hibernate4.SpringSessionContext");
    props.put("hibernate.jdbc.batch_size", "30");
    props.put("hibernate.enable_lazy_load_no_trans", "true");
    props.put("javax.persistence.validation.mode", "none");
    props.put("show_sql", "true");
    conf.addProperties(props);
    configurationProvider.invalidate();/*  w w  w .  j  ava2 s  . c om*/
}

From source file:org.ow2.bonita.env.descriptor.HibernateConfigurationDescriptor.java

License:Open Source License

@Override
public void initialize(final Object object, final WireContext wireContext) {
    final Configuration configuration = (Configuration) object;
    apply(mappingOperations, configuration, wireContext);
    apply(cacheOperations, configuration, wireContext);
    if (propertiesDescriptor != null) {
        final Properties properties = (Properties) wireContext.create(propertiesDescriptor, false);
        if (LOG.isLoggable(Level.FINE)) {
            LOG.fine("adding properties to hibernate configuration: " + properties);
        }/*w  w w  .  j a va2 s. c om*/
        configuration.addProperties(properties);
    }
    if (schemaOperation != null) {
        schemaOperation.apply(configuration, wireContext);
    }
}

From source file:org.ow2.proactive.resourcemanager.db.RMDBManager.java

License:Open Source License

private static RMDBManager createUsingProperties() {
    if (System.getProperty(JAVA_PROPERTYNAME_NODB) != null) {
        return createInMemoryRMDBManager();
    } else {/*from w w w.  j a v a2  s.com*/
        File configFile = new File(PAResourceManagerProperties
                .getAbsolutePath(PAResourceManagerProperties.RM_DB_HIBERNATE_CONFIG.getValueAsString()));

        boolean drop = PAResourceManagerProperties.RM_DB_HIBERNATE_DROPDB.getValueAsBoolean();
        boolean dropNS = PAResourceManagerProperties.RM_DB_HIBERNATE_DROPDB_NODESOURCES.getValueAsBoolean();

        if (logger.isInfoEnabled()) {
            logger.info("Starting RM DB Manager " + "with drop DB = " + drop + " and drop nodesources = "
                    + dropNS + " and configuration file = " + configFile.getAbsolutePath());
        }

        Configuration configuration = new Configuration();

        if (configFile.getName().endsWith(".xml")) {
            configuration.configure(configFile);
        } else {
            try {
                Properties properties = new Properties();
                properties.load(Files.newBufferedReader(configFile.toPath(), Charset.defaultCharset()));
                configuration.addProperties(properties);
            } catch (IOException e) {
                throw new IllegalArgumentException(e);
            }
        }

        return new RMDBManager(configuration, drop, dropNS);
    }
}

From source file:org.springframework.orm.hibernate3.LocalSessionFactoryBean.java

License:Apache License

@Override
@SuppressWarnings("unchecked")
protected SessionFactory buildSessionFactory() throws Exception {
    // Create Configuration instance.
    Configuration config = newConfiguration();

    DataSource dataSource = getDataSource();
    if (dataSource != null) {
        // Make given DataSource available for SessionFactory configuration.
        configTimeDataSourceHolder.set(dataSource);
    }//  ww  w. ja v  a 2s.co m
    if (this.jtaTransactionManager != null) {
        // Make Spring-provided JTA TransactionManager available.
        configTimeTransactionManagerHolder.set(this.jtaTransactionManager);
    }
    if (this.cacheRegionFactory != null) {
        // Make Spring-provided Hibernate RegionFactory available.
        configTimeRegionFactoryHolder.set(this.cacheRegionFactory);
    }
    if (this.lobHandler != null) {
        // Make given LobHandler available for SessionFactory configuration.
        // Do early because because mapping resource might refer to custom types.
        configTimeLobHandlerHolder.set(this.lobHandler);
    }

    // Analogous to Hibernate EntityManager's Ejb3Configuration:
    // Hibernate doesn't allow setting the bean ClassLoader explicitly,
    // so we need to expose it as thread context ClassLoader accordingly.
    Thread currentThread = Thread.currentThread();
    ClassLoader threadContextClassLoader = currentThread.getContextClassLoader();
    boolean overrideClassLoader = (this.beanClassLoader != null
            && !this.beanClassLoader.equals(threadContextClassLoader));
    if (overrideClassLoader) {
        currentThread.setContextClassLoader(this.beanClassLoader);
    }

    try {
        if (isExposeTransactionAwareSessionFactory()) {
            // Set Hibernate 3.1+ CurrentSessionContext implementation,
            // providing the Spring-managed Session as current Session.
            // Can be overridden by a custom value for the corresponding Hibernate property.
            config.setProperty(Environment.CURRENT_SESSION_CONTEXT_CLASS, SpringSessionContext.class.getName());
        }

        if (this.jtaTransactionManager != null) {
            // Set Spring-provided JTA TransactionManager as Hibernate property.
            config.setProperty(Environment.TRANSACTION_STRATEGY, JTATransactionFactory.class.getName());
            config.setProperty(Environment.TRANSACTION_MANAGER_STRATEGY,
                    LocalTransactionManagerLookup.class.getName());
        } else {
            // Makes the Hibernate Session aware of the presence of a Spring-managed transaction.
            // Also sets connection release mode to ON_CLOSE by default.
            config.setProperty(Environment.TRANSACTION_STRATEGY, SpringTransactionFactory.class.getName());
        }

        if (this.entityInterceptor != null) {
            // Set given entity interceptor at SessionFactory level.
            config.setInterceptor(this.entityInterceptor);
        }

        if (this.namingStrategy != null) {
            // Pass given naming strategy to Hibernate Configuration.
            config.setNamingStrategy(this.namingStrategy);
        }

        if (this.typeDefinitions != null) {
            // Register specified Hibernate type definitions.
            Mappings mappings = config.createMappings();
            for (TypeDefinitionBean typeDef : this.typeDefinitions) {
                mappings.addTypeDef(typeDef.getTypeName(), typeDef.getTypeClass(), typeDef.getParameters());
            }
        }

        if (this.filterDefinitions != null) {
            // Register specified Hibernate FilterDefinitions.
            for (FilterDefinition filterDef : this.filterDefinitions) {
                config.addFilterDefinition(filterDef);
            }
        }

        if (this.configLocations != null) {
            for (Resource resource : this.configLocations) {
                // Load Hibernate configuration from given location.
                config.configure(resource.getURL());
            }
        }

        if (this.hibernateProperties != null) {
            // Add given Hibernate properties to Configuration.
            config.addProperties(this.hibernateProperties);
        }

        if (dataSource != null) {
            Class<?> providerClass = LocalDataSourceConnectionProvider.class;
            if (isUseTransactionAwareDataSource() || dataSource instanceof TransactionAwareDataSourceProxy) {
                providerClass = TransactionAwareDataSourceConnectionProvider.class;
            } else if (config.getProperty(Environment.TRANSACTION_MANAGER_STRATEGY) != null) {
                providerClass = LocalJtaDataSourceConnectionProvider.class;
            }
            // Set Spring-provided DataSource as Hibernate ConnectionProvider.
            config.setProperty(Environment.CONNECTION_PROVIDER, providerClass.getName());
        }

        if (this.cacheRegionFactory != null) {
            // Expose Spring-provided Hibernate RegionFactory.
            config.setProperty(Environment.CACHE_REGION_FACTORY, LocalRegionFactoryProxy.class.getName());
        }

        if (this.mappingResources != null) {
            // Register given Hibernate mapping definitions, contained in resource files.
            for (String mapping : this.mappingResources) {
                Resource resource = new ClassPathResource(mapping.trim(), this.beanClassLoader);
                config.addInputStream(resource.getInputStream());
            }
        }

        if (this.mappingLocations != null) {
            // Register given Hibernate mapping definitions, contained in resource files.
            for (Resource resource : this.mappingLocations) {
                config.addInputStream(resource.getInputStream());
            }
        }

        if (this.cacheableMappingLocations != null) {
            // Register given cacheable Hibernate mapping definitions, read from the file system.
            for (Resource resource : this.cacheableMappingLocations) {
                config.addCacheableFile(resource.getFile());
            }
        }

        if (this.mappingJarLocations != null) {
            // Register given Hibernate mapping definitions, contained in jar files.
            for (Resource resource : this.mappingJarLocations) {
                config.addJar(resource.getFile());
            }
        }

        if (this.mappingDirectoryLocations != null) {
            // Register all Hibernate mapping definitions in the given directories.
            for (Resource resource : this.mappingDirectoryLocations) {
                File file = resource.getFile();
                if (!file.isDirectory()) {
                    throw new IllegalArgumentException(
                            "Mapping directory location [" + resource + "] does not denote a directory");
                }
                config.addDirectory(file);
            }
        }

        // Tell Hibernate to eagerly compile the mappings that we registered,
        // for availability of the mapping information in further processing.
        postProcessMappings(config);
        config.buildMappings();

        if (this.entityCacheStrategies != null) {
            // Register cache strategies for mapped entities.
            for (Enumeration<?> classNames = this.entityCacheStrategies.propertyNames(); classNames
                    .hasMoreElements();) {
                String className = (String) classNames.nextElement();
                String[] strategyAndRegion = StringUtils
                        .commaDelimitedListToStringArray(this.entityCacheStrategies.getProperty(className));
                if (strategyAndRegion.length > 1) {
                    config.setCacheConcurrencyStrategy(className, strategyAndRegion[0], strategyAndRegion[1]);
                } else if (strategyAndRegion.length > 0) {
                    config.setCacheConcurrencyStrategy(className, strategyAndRegion[0]);
                }
            }
        }

        if (this.collectionCacheStrategies != null) {
            // Register cache strategies for mapped collections.
            for (Enumeration<?> collRoles = this.collectionCacheStrategies.propertyNames(); collRoles
                    .hasMoreElements();) {
                String collRole = (String) collRoles.nextElement();
                String[] strategyAndRegion = StringUtils
                        .commaDelimitedListToStringArray(this.collectionCacheStrategies.getProperty(collRole));
                if (strategyAndRegion.length > 1) {
                    config.setCollectionCacheConcurrencyStrategy(collRole, strategyAndRegion[0],
                            strategyAndRegion[1]);
                } else if (strategyAndRegion.length > 0) {
                    config.setCollectionCacheConcurrencyStrategy(collRole, strategyAndRegion[0]);
                }
            }
        }

        if (this.eventListeners != null) {
            // Register specified Hibernate event listeners.
            for (Map.Entry<String, Object> entry : this.eventListeners.entrySet()) {
                String listenerType = entry.getKey();
                Object listenerObject = entry.getValue();
                if (listenerObject instanceof Collection) {
                    Collection<Object> listeners = (Collection<Object>) listenerObject;
                    EventListeners listenerRegistry = config.getEventListeners();
                    Object[] listenerArray = (Object[]) Array
                            .newInstance(listenerRegistry.getListenerClassFor(listenerType), listeners.size());
                    listenerArray = listeners.toArray(listenerArray);
                    config.setListeners(listenerType, listenerArray);
                } else {
                    config.setListener(listenerType, listenerObject);
                }
            }
        }

        // Perform custom post-processing in subclasses.
        postProcessConfiguration(config);

        // Build SessionFactory instance.
        logger.info("Building new Hibernate SessionFactory");
        this.configuration = config;
        return newSessionFactory(config);
    }

    finally {
        if (dataSource != null) {
            configTimeDataSourceHolder.remove();
        }
        if (this.jtaTransactionManager != null) {
            configTimeTransactionManagerHolder.remove();
        }
        if (this.cacheRegionFactory != null) {
            configTimeRegionFactoryHolder.remove();
        }
        if (this.lobHandler != null) {
            configTimeLobHandlerHolder.remove();
        }
        if (overrideClassLoader) {
            // Reset original thread context ClassLoader.
            currentThread.setContextClassLoader(threadContextClassLoader);
        }
    }
}

From source file:org.wso2.security.tools.reposcanner.storage.JDBCStorage.java

License:Open Source License

public JDBCStorage(String driverName, String connectionUri, String username, char[] password,
        String hibernateDialect) {
    try {//w w w.  ja v  a 2s .c  om
        Properties properties = new Properties();
        properties.put("hibernate.connection.driver_class", driverName);
        properties.put("hibernate.connection.url", connectionUri);
        properties.put("hibernate.connection.username", username);
        properties.put("hibernate.connection.password", new String(password));
        properties.put("hibernate.dialect", hibernateDialect);
        if (AppConfig.isCreateDB()) {
            properties.put("hibernate.hbm2ddl.auto", "create");
        }
        if (AppConfig.isDebug()) {
            properties.put("hibernate.show_sql", "true");
            properties.put("hibernate.format_sql", "true");
        }

        Configuration configuration = new Configuration();
        configuration.addProperties(properties);

        configuration.addAnnotatedClass(Repo.class);
        configuration.addAnnotatedClass(RepoArtifact.class);
        configuration.addAnnotatedClass(RepoError.class);

        sessionFactory = configuration.buildSessionFactory();

        for (int i = 0; i < password.length; i++) {
            password[i] = ' ';
        }
    } catch (Throwable ex) {
        log.fatal("Failed to create sessionFactory object. Terminating..." + ex);
        throw ex;
    }
}

From source file:owldb.util.HibernateUtil.java

License:Open Source License

/**
 * Constructor./*from   w w w . jav a 2s.c  o m*/
 * 
 * @param ontologyManager The owl ontology manager
 * @param hibernateProperties Additional Hibernate settings
 */
public HibernateUtil(final OWLOntologyManager ontologyManager, final Properties hibernateProperties) {
    try {
        final Configuration configuration = new Configuration();
        configuration.configure();
        final Interceptor interceptor = new OWLDBInterceptor(ontologyManager);
        configuration.setInterceptor(interceptor);

        final EventListeners listeners = configuration.getEventListeners();
        final OWLDBEventListener dbListener = new OWLDBEventListener();
        listeners.setSaveOrUpdateEventListeners(
                new SaveOrUpdateEventListener[] { dbListener, new DefaultSaveOrUpdateEventListener() });
        listeners.setSaveEventListeners(
                new SaveOrUpdateEventListener[] { dbListener, new DefaultSaveEventListener() });
        listeners.setPostCommitDeleteEventListeners(new PostDeleteEventListener[] { dbListener });
        listeners.setPostCommitInsertEventListeners(new PostInsertEventListener[] { dbListener });

        // Enable second level cache if not set otherwise
        if (hibernateProperties.get(Environment.USE_SECOND_LEVEL_CACHE) == null)
            hibernateProperties.setProperty(Environment.USE_SECOND_LEVEL_CACHE, "true");
        // Enable query cache if not set otherwise and second level is enabled
        if ("true".equals(hibernateProperties.get(Environment.USE_SECOND_LEVEL_CACHE))
                && hibernateProperties.get(Environment.USE_QUERY_CACHE) == null)
            hibernateProperties.setProperty(Environment.USE_QUERY_CACHE, "true");

        // Add additional specific Hibernate properties
        configuration.addProperties(hibernateProperties);

        // Create the SessionFactory from the configuration.
        this.factory = configuration.buildSessionFactory();
    } catch (final Throwable ex) {
        LOGGER.error("Initial SessionFactory creation failed.", ex);
        throw new ExceptionInInitializerError(ex);
    }
}

From source file:ru.apertum.journal.db.HibernateUtil.java

License:Open Source License

private HibernateUtil() {
    try {// w  ww . ja v a  2s. c o  m
        final Configuration configuration = new Configuration();
        configuration.configure("/ru/apertum/journal/cfg/hibernate.cfg.xml");
        final Properties prop = new Properties();
        final File f = new File("config/journal.properties");
        if (f.exists()) {
            prop.load(new FileInputStream(f));
        }
        configuration.addProperties(prop);
        final ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
                .applySettings(configuration.getProperties()).build();
        sessionFactory = configuration.buildSessionFactory(serviceRegistry);
    } catch (Throwable ex) {
        // Log exception!
        throw new ExceptionInInitializerError(ex);
    }
    //sessionFactory = new AnnotationConfiguration().addAnnotatedClass(Book.class).buildSessionFactory();
}