List of usage examples for org.hibernate.cfg Configuration setProperty
public Configuration setProperty(String propertyName, String value)
From source file:org.ow2.proactive.resourcemanager.db.RMDBManager.java
License:Open Source License
private static RMDBManager createInMemoryRMDBManager() { Configuration config = new Configuration(); config.setProperty("hibernate.connection.driver_class", "org.hsqldb.jdbc.JDBCDriver"); config.setProperty("hibernate.connection.url", "jdbc:hsqldb:mem:" + System.currentTimeMillis() + ";hsqldb.tx=mvcc"); config.setProperty("hibernate.dialect", "org.hibernate.dialect.HSQLDialect"); return new RMDBManager(config, true, true); }
From source file:org.ow2.proactive.resourcemanager.db.RMDBManager.java
License:Open Source License
/** * Used only for testing purposes of the hibernate config needs to be changed. * RMDBManager.getInstance() should be used in most of cases. *//* w w w. j a v a 2 s .c om*/ public RMDBManager(Configuration configuration, boolean drop, boolean dropNS) { try { configuration.addAnnotatedClass(NodeSourceData.class); configuration.addAnnotatedClass(NodeHistory.class); configuration.addAnnotatedClass(UserHistory.class); configuration.addAnnotatedClass(Alive.class); if (drop) { configuration.setProperty("hibernate.hbm2ddl.auto", "create"); // dropping RRD data base as well File ddrDB = new File(PAResourceManagerProperties.RM_HOME.getValueAsString() + System.getProperty("file.separator") + PAResourceManagerProperties.RM_RRD_DATABASE_NAME.getValueAsString()); if (ddrDB.exists()) { ddrDB.delete(); } } configuration.setProperty("hibernate.id.new_generator_mappings", "true"); configuration.setProperty("hibernate.jdbc.use_streams_for_binary", "true"); sessionFactory = configuration.buildSessionFactory(); List<?> lastAliveTime = sqlQuery("from Alive"); if (lastAliveTime == null || lastAliveTime.size() == 0) { createRmAliveTime(); } else if (!drop) { if (dropNS) { removeNodeSources(); } recover(((Alive) lastAliveTime.get(0)).getTime()); } int periodInMilliseconds = PAResourceManagerProperties.RM_ALIVE_EVENT_FREQUENCY.getValueAsInt(); timer = new Timer("Periodic RM live event saver"); timer.schedule(new TimerTask() { @Override public void run() { updateRmAliveTime(); } }, periodInMilliseconds, periodInMilliseconds); } catch (Throwable ex) { logger.error("Initial SessionFactory creation failed", ex); throw new DatabaseManagerException("Initial SessionFactory creation failed", ex); } }
From source file:org.paxle.data.db.impl.ConnectionUrlTool.java
License:Open Source License
public static void postProcessProperties(Configuration configuration) { // getting db-config-properties Properties configProps = configuration.getProperties(); String connectionURL = configProps.getProperty("connection.url"); if (connectionURL != null) { configuration.setProperty("connection.url", processProperty(connectionURL)); }//from w w w.jav a 2 s . com connectionURL = configProps.getProperty("hibernate.connection.url"); if (connectionURL != null) { configuration.setProperty("hibernate.connection.url", processProperty(connectionURL)); } }
From source file:org.photovault.common.MysqlDescriptor.java
License:Open Source License
/** * Cretes Hibernate configuration for accessing the database. * @param username MySql user name//from w ww . j a va 2 s . c om * @param passwd password for user * @return The Hibernate configuration * @throws org.photovault.common.PhotovaultException Not thrown by this * class. */ public Configuration initHibernate(String username, String passwd) throws PhotovaultException { Configuration cfg = new AnnotationConfiguration(); cfg.configure(); cfg.setProperty("hibernate.connection.driver_class", "com.mysql.jdbc.Driver"); cfg.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLDialect"); cfg.setProperty("hibernate.connection.url", "jdbc:mysql://" + host + "/" + dbname); cfg.setProperty("hibernate.connection.username", username); cfg.setProperty("hibernate.connection.password", passwd); return cfg; }
From source file:org.s23m.cell.eclipse.connector.database.DatabaseConnectorSupport.java
License:Mozilla Public License
public static Configuration buildConfiguration(final DatabaseConnector connector, final String hostname, final int port, final String databaseName, final String username, final String password) { try {/*from w w w . ja v a2 s . c om*/ final Configuration config = new Configuration(); config.setProperty("hibernate.dialect", connector.getDialect()); config.setProperty("hibernate.connection.driver_class", connector.getDriverClass()); config.setProperty("hibernate.connection.url", connector.createConnectionUrl(hostname, port, databaseName)); config.setProperty("hibernate.connection.username", username); config.setProperty("hibernate.connection.password", password); config.setProperty("hibernate.default_schema", databaseName); config.setProperty("hibernate.jdbc.batch_size", "50"); config.setProperty("hibernate.show_sql", "false"); return config; } catch (final Exception e) { return null; } }
From source file:org.snaker.engine.access.hibernate.HibernateHelper.java
License:Apache License
/** * SessionFactoryhibernate.cfg.xml?sessionFactory * ?Configuration.initAccessDBObjectsessionfactory * ioc/*from w w w .j a v a2s . c om*/ */ private static void initialize() { String driver = ConfigHelper.getProperty("jdbc.driver"); String url = ConfigHelper.getProperty("jdbc.url"); String username = ConfigHelper.getProperty("jdbc.username"); String password = ConfigHelper.getProperty("jdbc.password"); String dialect = ConfigHelper.getProperty("hibernate.dialect"); AssertHelper.notNull(driver); AssertHelper.notNull(url); AssertHelper.notNull(username); AssertHelper.notNull(password); AssertHelper.notNull(dialect); String formatSql = ConfigHelper.getProperty("hibernate.format_sql"); String showSql = ConfigHelper.getProperty("hibernate.show_sql"); Configuration configuration = new Configuration(); if (StringHelper.isNotEmpty(driver)) { configuration.setProperty("hibernate.connection.driver_class", driver); } if (StringHelper.isNotEmpty(url)) { configuration.setProperty("hibernate.connection.url", url); } if (StringHelper.isNotEmpty(username)) { configuration.setProperty("hibernate.connection.username", username); } if (StringHelper.isNotEmpty(password)) { configuration.setProperty("hibernate.connection.password", password); } if (StringHelper.isNotEmpty(dialect)) { configuration.setProperty("hibernate.dialect", dialect); } if (StringHelper.isNotEmpty(formatSql)) { configuration.setProperty("hibernate.format_sql", formatSql); } if (StringHelper.isNotEmpty(showSql)) { configuration.setProperty("hibernate.show_sql", showSql); } sessionFactory = configuration.configure().buildSessionFactory(); }
From source file:org.sns.tool.hibernate.dbdd.DatabaseDesignGeneratorTask.java
License:Open Source License
public void execute() throws BuildException { if (hibernateConfigClass == null) throw new BuildException("hibernateConfigClass was not provided."); if (structureRulesClass == null) throw new BuildException("structureRulesClass was not provided."); if (docBookFile == null) throw new BuildException("indexFile was not provided."); try {/*from w w w. ja va2 s .c o m*/ final Configuration configuration = (Configuration) hibernateConfigClass.newInstance(); if (hibernateConfigFile != null) configuration.configure(hibernateConfigFile); final TableStructure structure; if (structureClass == null) { final TableStructureRules rules = (TableStructureRules) structureRulesClass.newInstance(); structure = new DefaultTableStructure(configuration, rules); } else { final Constructor ctr = structureClass .getConstructor(new Class[] { Configuration.class, TableStructureRules.class }); final TableStructureRules rules = (TableStructureRules) structureRulesClass.newInstance(); structure = (TableStructure) ctr.newInstance(new Object[] { configuration, rules }); } if (dialectClass != null) configuration.setProperty(Environment.DIALECT, dialectClass); final DatabaseDiagramRenderer ddr = (DatabaseDiagramRenderer) databaseDiagramRendererClass .newInstance(); final MappedClassDocumentationProviders mcdp = (MappedClassDocumentationProviders) mappedClassDocumentationProvidersClass .newInstance(); log("Using Hibernate Configuration " + configuration.getClass()); log("Using Structure " + structure.getClass()); log("Using Structure Rules " + structure.getRules().getClass()); log("Using Dialect " + configuration.getProperty(Environment.DIALECT)); log("Using Renderer " + ddr.getClass()); log("Using Mapped Class Documentation Providers " + mcdp.getClass()); final ByteArrayOutputStream graphvizCmdOutputStreamBuffer = new ByteArrayOutputStream(); final PrintStream graphvizCmdOutputStream = new PrintStream(graphvizCmdOutputStreamBuffer); final DatabaseDesignGeneratorConfig ddgConfig = new DatabaseDesignGeneratorConfig() { public File getImagesDirectory() { return destDir == null ? docBookFile.getParentFile() : destDir; } public Configuration getHibernateConfiguration() { return configuration; } public File getDocBookFile() { return docBookFile; } public File getAssociatedJavaDocHome() { return associatedJavaDocHome; } public String getDocumentTitle() { return documentTitle == null ? "No documentTitle attribute provided." : documentTitle; } public TableStructure getTableStructure() { return structure; } public DatabaseDiagramRenderer getDatabaseDiagramRenderer() { return ddr; } public MappedClassDocumentationProviders getMappedClassDocumentationProviders() { return mcdp; } public String getGraphvizDiagramOutputType() { return graphvizDotOutputType; } public String getGraphVizDotCommandSpec() { return graphvizDotCmdSpec; } public PrintStream getGraphVizDotLogOutputStream() { return graphvizCmdOutputStream; } }; final DatabaseDesignGenerator ddg = new DatabaseDesignGenerator(ddgConfig); ddg.generateDatabaseDesign(); if (logGraphvizOutput) log(graphvizCmdOutputStreamBuffer.toString()); } catch (Exception e) { throw new BuildException(e); } }
From source file:org.sns.tool.hibernate.document.diagram.HibernateDiagramGeneratorTask.java
License:Open Source License
public void execute() throws BuildException { if (hibernateConfigClass == null) throw new BuildException("hibernateConfigClass was not provided."); if (diagramFilterClass == null) throw new BuildException("diagramFilterClass was not provided."); try {//www. j a va2 s. co m final HibernateDiagramGeneratorFilter filter = (HibernateDiagramGeneratorFilter) diagramFilterClass .newInstance(); log("Using diagram filter " + filter.getClass()); final Configuration configuration = (Configuration) hibernateConfigClass.newInstance(); log("Using configuration " + configuration.getClass()); if (dialectClass != null) { configuration.setProperty(Environment.DIALECT, dialectClass); log("Using dialect " + configuration.getProperty(Environment.DIALECT)); } if (hibernateConfigFile != null) { configuration.configure(hibernateConfigFile); log("Using config file " + hibernateConfigFile); } final GraphvizDiagramGenerator gdg = new GraphvizDiagramGenerator(diagramId, true, GraphvizLayoutType.DOT); final HibernateDiagramGenerator hdg = new HibernateDiagramGenerator(configuration, gdg, filter); hdg.generate(); gdg.generateDOTSource(dotFile); log("DOT file " + dotFile + " written."); } catch (IllegalAccessException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } catch (IOException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } catch (InstantiationException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } }
From source file:org.specrunner.hibernate3.PluginConfiguration.java
License:Open Source License
/** * Change URL if thread safe is true./* www . java2 s. c om*/ * * @param context * The context. * @param cfg * The configuration. */ protected void changeUrl(IContext context, Configuration cfg) { String url = String .valueOf(SRServices.get(IConcurrentMapping.class).get("url", cfg.getProperty(Environment.URL))); cfg.setProperty(Environment.URL, url); Node node = context.getNode(); if (node instanceof Element) { Element ele = (Element) node; Attribute att = ele.getAttribute("title"); if (att == null) { att = new Attribute("title", ""); ele.addAttribute(att); } att.setValue("URL='" + url + "'"); } if (UtilLog.LOG.isInfoEnabled()) { UtilLog.LOG.info("Connection URL set to '" + url + "'."); } }
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); }// w w w . j a v a2 s.c o 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); } } }