List of usage examples for org.hibernate.cfg Configuration buildMappings
@Deprecated public void buildMappings()
From source file:org.beangle.orm.hibernate.tool.ConfigBuilder.java
License:Open Source License
/** * build configration//from w w w .j av a 2s . co m * * @throws Exception */ @SuppressWarnings("unchecked") public static Configuration build(Configuration cfg) throws Exception { PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver( DdlGenerator.class.getClassLoader()); // config naming strategy DefaultTableNamingStrategy tableNamingStrategy = new DefaultTableNamingStrategy(); for (Resource resource : resolver.getResources("classpath*:META-INF/beangle/table.properties")) tableNamingStrategy.addConfig(resource.getURL()); RailsNamingStrategy namingStrategy = new RailsNamingStrategy(); namingStrategy.setTableNamingStrategy(tableNamingStrategy); cfg.setNamingStrategy(namingStrategy); for (Resource resource : resolver.getResources("classpath*:META-INF/hibernate.cfg.xml")) cfg.configure(resource.getURL()); for (Resource resource : resolver.getResources("classpath*:META-INF/beangle/persist*.properties")) { InputStream is = resource.getURL().openStream(); Properties props = new Properties(); if (null != is) props.load(is); Object module = props.remove("module"); if (null == module) continue; Class<? extends AbstractPersistModule> moduleClass = (Class<? extends AbstractPersistModule>) ClassLoaders .loadClass(module.toString()); addPersistInfo(cfg, moduleClass.newInstance().getConfig()); Enumeration<String> enumer = (Enumeration<String>) props.propertyNames(); while (enumer.hasMoreElements()) { String propertyName = enumer.nextElement(); cfg.setProperty(propertyName, props.getProperty(propertyName)); } IOs.close(is); } cfg.buildMappings(); return cfg; }
From source file:org.bonitasoft.engine.persistence.HibernateConfigurationProviderImpl.java
License:Open Source License
protected Configuration buildConfiguration(final Properties properties, final HibernateResourcesConfigurationProvider hibernateResourcesConfigurationProvider) { final Configuration configuration = new Configuration(); configuration.addProperties(properties); for (final String resource : hibernateResourcesConfigurationProvider.getResources()) { configuration.addResource(resource); }/* www . j av a 2s . c o m*/ configuration.buildMappings(); return configuration; }
From source file:org.codehaus.mojo.appfuse.mojo.DbToXMLMojo.java
License:Apache License
/** * This method will run the database conversion to hbm file mojo task. * /*from w w w .ja v a2s . c o m*/ * @throws MojoExecutionException * Thrown if we fail to obtain an appfuse resource. */ public void execute() throws MojoExecutionException { if (getLog().isInfoEnabled()) { getLog().info("Running the " + this.getMojoName() + " Mojo with properties " + this); } // Get a Hibernate Mapping Exporter HibernateMappingExporter exporter = new HibernateMappingExporter(); Properties properties = new Properties(); // Set any custom properties that might have been passed in. exporter.setProperties(properties); // create a new JDBC configuration object. JDBCConfigurationUtility configurationUtility = new JDBCConfigurationUtility(); // call create to set up the configuration. Configuration configuration = configurationUtility.createConfiguration(); // Set some parameters in the configuration class. if ((this.getModelPackageName() != null) && (this.getModelPackageName().length() > 0)) { configurationUtility.setPackageName(this.getModelPackageName()); } else { throw new MojoExecutionException("Model package name cannot be null or empty"); } if ((this.getDatabasePropertiesFile() != null) && (this.getDatabasePropertiesFile().length() > 0)) { configurationUtility.setPropertyFile(new File(this.getDatabasePropertiesFile())); } else { throw new MojoExecutionException("Hibernate properties file cannot be null or empty"); } // Load the reverse engineering configuration xml files. if ((this.getReverseEngineeringConfigurationFile() == null) || (this.getReverseEngineeringConfigurationFile().length() == 0)) { throw new MojoExecutionException("There must be at least one reverse engineering xml file defined"); } configurationUtility.addRevEngFile(this.getReverseEngineeringConfigurationFile()); // Set the reverse engineering strategy class if ((this.getReverseStrategyClass() != null) && (this.getReverseStrategyClass().length() > 0)) { configurationUtility.setReverseStrategy(this.getReverseStrategyClass()); } // complete the configuration processing configurationUtility.doConfiguration(configuration); configuration.buildMappings(); // set the configurator into the exporter exporter.setConfiguration(configuration); // Set the destination directory if ((this.getOutputDirectory() != null) && (this.getOutputDirectory().length() > 0)) { exporter.setOutputDirectory(new File(this.getOutputDirectory())); } else { throw new MojoExecutionException("Output directory cannot be null or empty"); } // Set the template information. exporter.setTemplateName(this.getHbmTemplateName()); // run the exporter. exporter.start(); }
From source file:org.jboss.tools.hibernate3_6.console.ConsoleExtension3_6.java
License:Open Source License
private Configuration buildConfiguration(final ExporterAttributes attributes, HibernateExtension3_6 cc, IWorkspaceRoot root) {/* w ww . j av a 2 s . co m*/ final boolean reveng = attributes.isReverseEngineer(); final String reverseEngineeringStrategy = attributes.getRevengStrategy(); final boolean preferBasicCompositeids = attributes.isPreferBasicCompositeIds(); final IResource revengres = PathHelper.findMember(root, attributes.getRevengSettings()); if (reveng) { Configuration configuration = null; if (cc.hasConfiguration()) { configuration = cc.getConfiguration(); } else { configuration = cc.buildWith(null, false); } final JDBCMetaDataConfiguration cfg = new JDBCMetaDataConfiguration(); Properties properties = configuration.getProperties(); cfg.setProperties(properties); cc.buildWith(cfg, false); cfg.setPreferBasicCompositeIds(preferBasicCompositeids); cc.execute(new Command() { // need to execute in the consoleconfiguration to let it handle classpath stuff! public Object execute() { //todo: factor this setup of revengstrategy to core ReverseEngineeringStrategy res = new DefaultReverseEngineeringStrategy(); OverrideRepository repository = null; if (revengres != null) { File file = PathHelper.getLocation(revengres).toFile(); repository = new OverrideRepository(); repository.addFile(file); } if (repository != null) { res = repository.getReverseEngineeringStrategy(res); } if (reverseEngineeringStrategy != null && reverseEngineeringStrategy.trim().length() > 0) { res = loadreverseEngineeringStrategy(reverseEngineeringStrategy, res); } ReverseEngineeringSettings qqsettings = new ReverseEngineeringSettings(res) .setDefaultPackageName(attributes.getPackageName()) .setDetectManyToMany(attributes.detectManyToMany()) //.setDetectOneToOne( attributes.detectOneToOne() ) .setDetectOptimisticLock(attributes.detectOptimisticLock()); res.setSettings(qqsettings); cfg.setReverseEngineeringStrategy(res); cfg.readFromJDBC(); cfg.buildMappings(); return null; } }); return cfg; } else { cc.build(); final Configuration configuration = cc.getConfiguration(); cc.execute(new Command() { public Object execute() { configuration.buildMappings(); return configuration; } }); return configuration; } }
From source file:org.jboss.tools.hibernate4_0.console.ConsoleExtension4_0.java
License:Open Source License
private Configuration buildConfiguration(final ExporterAttributes attributes, HibernateExtension4_0 cc, IWorkspaceRoot root) {/*w w w. j a v a2s . com*/ final boolean reveng = attributes.isReverseEngineer(); final String reverseEngineeringStrategy = attributes.getRevengStrategy(); final boolean preferBasicCompositeids = attributes.isPreferBasicCompositeIds(); final IResource revengres = PathHelper.findMember(root, attributes.getRevengSettings()); if (reveng) { Configuration configuration = null; if (cc.hasConfiguration()) { configuration = cc.getConfiguration(); } else { configuration = cc.buildWith(null, false); } final JDBCMetaDataConfiguration cfg = new JDBCMetaDataConfiguration(); Properties properties = configuration.getProperties(); cfg.setProperties(properties); cc.buildWith(cfg, false); cfg.setPreferBasicCompositeIds(preferBasicCompositeids); cc.execute(new Command() { // need to execute in the consoleconfiguration to let it handle classpath stuff! public Object execute() { //todo: factor this setup of revengstrategy to core ReverseEngineeringStrategy res = new DefaultReverseEngineeringStrategy(); OverrideRepository repository = null; if (revengres != null) { File file = PathHelper.getLocation(revengres).toFile(); repository = new OverrideRepository(); repository.addFile(file); } if (repository != null) { res = repository.getReverseEngineeringStrategy(res); } if (reverseEngineeringStrategy != null && reverseEngineeringStrategy.trim().length() > 0) { res = loadreverseEngineeringStrategy(reverseEngineeringStrategy, res); } ReverseEngineeringSettings qqsettings = new ReverseEngineeringSettings(res) .setDefaultPackageName(attributes.getPackageName()) .setDetectManyToMany(attributes.detectManyToMany()) //.setDetectOneToOne( attributes.detectOneToOne() ) .setDetectOptimisticLock(attributes.detectOptimisticLock()); res.setSettings(qqsettings); cfg.setReverseEngineeringStrategy(res); cfg.readFromJDBC(); cfg.buildMappings(); return null; } }); return cfg; } else { cc.build(); final Configuration configuration = cc.getConfiguration(); cc.execute(new Command() { public Object execute() { configuration.buildMappings(); return configuration; } }); return configuration; } }
From source file:org.jbpm.test.Db.java
License:Open Source License
public static void clean(ProcessEngine processEngine) { SessionFactory sessionFactory = processEngine.get(SessionFactory.class); // when running this with a remote ejb invocation configuration, there is no // session factory and no cleanup needs to be done if (sessionFactory == null) { return;/*from ww w.j a v a 2 s .co m*/ } String[] cleanSql = cleanSqlCache.get(processEngine); if (cleanSql == null) { Configuration configuration = processEngine.get(Configuration.class); SessionFactoryImplementor sessionFactoryImplementor = (SessionFactoryImplementor) sessionFactory; Dialect dialect = sessionFactoryImplementor.getDialect(); // loop over all foreign key constraints List<String> dropForeignKeysSql = new ArrayList<String>(); List<String> createForeignKeysSql = new ArrayList<String>(); Iterator<Table> iter = configuration.getTableMappings(); //if no session-factory is build, the configuration is not fully initialized. //Hence, the ForeignKey's won't have a referenced table. This is calculated on //second pass. configuration.buildMappings(); while (iter.hasNext()) { Table table = (Table) iter.next(); if (table.isPhysicalTable()) { String catalog = table.getCatalog(); String schema = table.getSchema(); Iterator<ForeignKey> subIter = table.getForeignKeyIterator(); while (subIter.hasNext()) { ForeignKey fk = (ForeignKey) subIter.next(); if (fk.isPhysicalConstraint()) { // collect the drop foreign key constraint sql dropForeignKeysSql.add(fk.sqlDropString(dialect, catalog, schema)); // MySQLDialect creates an index for each foreign key. // see // http://opensource.atlassian.com/projects/hibernate/browse/HHH-2155 // This index should be dropped or an error will be thrown during // the creation phase if (dialect instanceof MySQLDialect) { dropForeignKeysSql .add("alter table " + table.getName() + " drop key " + fk.getName()); } // and collect the create foreign key constraint sql createForeignKeysSql .add(fk.sqlCreateString(dialect, sessionFactoryImplementor, catalog, schema)); } } } } List<String> deleteSql = new ArrayList<String>(); iter = configuration.getTableMappings(); while (iter.hasNext()) { Table table = (Table) iter.next(); if (table.isPhysicalTable()) { deleteSql.add("delete from " + table.getName()); } } // glue // - drop foreign key constraints // - delete contents of all tables // - create foreign key constraints // together to form the clean script List<String> cleanSqlList = new ArrayList<String>(); cleanSqlList.addAll(dropForeignKeysSql); cleanSqlList.addAll(deleteSql); cleanSqlList.addAll(createForeignKeysSql); cleanSql = (String[]) cleanSqlList.toArray(new String[cleanSqlList.size()]); cleanSqlCache.put(processEngine, cleanSql); } Session session = sessionFactory.openSession(); try { for (String query : cleanSql) { // log.trace(query); session.createSQLQuery(query).executeUpdate(); } } finally { session.close(); } }
From source file:org.openeos.hibernate.internal.configurators.FilterConfigurator.java
License:Apache License
private void addFilterDefinitions(FilterProvider provider, ConfigurationProvider configurationProvider) { Configuration conf = configurationProvider.getConfiguration(); conf.buildMappings(); Map<?, ?> filterDefinitions = conf.getFilterDefinitions(); TypeResolver resolver = conf.getTypeResolver(); for (BasicFilterDefinition filterDef : provider.getFilterDefinitions()) { Map<String, Type> paramMapConverted = new HashMap<String, Type>(); for (Entry<String, String> paramEntry : filterDef.getParameterTypeMap().entrySet()) { Type type = resolver.heuristicType(paramEntry.getValue()); paramMapConverted.put(paramEntry.getKey(), type); }/*from ww w. ja v a2 s . c o m*/ FilterDefinition definition = new FilterDefinition(filterDef.getName(), filterDef.getDefaultCondition(), paramMapConverted); LOG.debug("Registering new filter definition with name '{}'", definition.getFilterName()); if (filterDefinitions.containsKey(definition.getFilterName())) { LOG.warn("The configuration already has filter definition with name '{}', overwriting.", definition.getFilterName()); } conf.addFilterDefinition(definition); filterProviderMap.put(definition.getFilterName(), provider); Iterator<PersistentClass> classIterator = conf.getClassMappings(); while (classIterator.hasNext()) { PersistentClass persistentClass = classIterator.next(); provider.addFilterToClassIfNecesary(persistentClass, filterDef); } } configurationProvider.invalidate(); }
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); }/*www. j a v a2s . 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); } } }
From source file:org.uengine.edu.oop.soc.model.OopsocsamplePersistentManager.java
@Override public Configuration createConfiguration() { Configuration configuration = new Configuration(); configuration.addAnnotatedClass(org.uengine.edu.oop.soc.model.Account.class); configuration.buildMappings(); return configuration; }
From source file:org.unitime.commons.hibernate.util.HibernateUtil.java
License:Open Source License
public static void fixSchemaInFormulas(Configuration cfg) { cfg.buildMappings(); String schema = cfg.getProperty("default_schema"); if (schema != null) { for (Iterator i = cfg.getClassMappings(); i.hasNext();) { PersistentClass pc = (PersistentClass) i.next(); for (Iterator j = pc.getPropertyIterator(); j.hasNext();) { Property p = (Property) j.next(); for (Iterator k = p.getColumnIterator(); k.hasNext();) { Selectable c = (Selectable) k.next(); if (c instanceof Formula) { Formula f = (Formula) c; if (f.getFormula() != null && f.getFormula().indexOf("%SCHEMA%") >= 0) { f.setFormula(f.getFormula().replaceAll("%SCHEMA%", schema)); sLog.debug("Schema updated in " + pc.getClassName() + "." + p.getName() + " to " + f.getFormula()); }// www. j av a 2 s. c om } } } } } }