Example usage for org.hibernate.cfg Configuration addDirectory

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

Introduction

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

Prototype

public Configuration addDirectory(File dir) throws MappingException 

Source Link

Document

Read all mapping documents from a directory tree.

Usage

From source file:com.cyclopsgroup.tornado.maven.GeneratePojoMojo.java

License:Open Source License

/**
 * Overwrite or implement parent method/*from w  ww  .j  av  a  2 s. c o  m*/
 *
 * @see com.cyclopsgroup.tornado.maven.AbstractHibernateMojoBase#execute(org.apache.avalon.framework.service.ServiceManager)
 */
public void execute(ServiceManager serviceManager) throws Exception {
    Configuration conf = new Configuration();
    conf.addDirectory(getSchemaDirectory());

    POJOExporter exporter = new POJOExporter(conf, pojoDirectory);
    exporter.getProperties().setProperty("jdk5", Boolean.valueOf(jdk5).toString());
    exporter.getProperties().setProperty("ejb3", Boolean.valueOf(ejb3).toString());
    exporter.setTemplateName("Pojo");
    exporter.start();
}

From source file:com.frameworkset.common.poolman.hibernate.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) {
        this.configTimeDataSourceHolder.set(dataSource);
    }/*ww w .  j a  v a2 s.  com*/
    // 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));
    try {
        if (overrideClassLoader) {
            currentThread.setContextClassLoader(this.beanClassLoader);
        }

        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.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.
            Properties temp = new Properties();
            temp.putAll(this.hibernateProperties);
            config.addProperties(temp);
        }

        if (dataSource != null) {
            Class providerClass = LocalDataSourceConnectionProvider.class;

            config.setProperty(Environment.CONNECTION_PROVIDER, providerClass.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 = SimpleStringUtil
                        .commaDelimitedListToStringArray(this.entityCacheStrategies.getProperty(className));
                if (strategyAndRegion.length > 1) {
                    // method signature declares return type as Configuration on Hibernate 3.6
                    // but as void on Hibernate 3.3 and 3.5
                    Method setCacheConcurrencyStrategy = Configuration.class
                            .getMethod("setCacheConcurrencyStrategy", String.class, String.class, String.class);
                    ReflectionUtils.invokeMethod(setCacheConcurrencyStrategy, config,
                            new Object[] { 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 = SimpleStringUtil
                        .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 (overrideClassLoader) {
            // Reset original thread context ClassLoader.
            currentThread.setContextClassLoader(threadContextClassLoader);
        }
        configTimeDataSourceHolder.set(null);
    }
}

From source file:com.mg.jet.birt.report.data.oda.ejbql.HibernateUtil.java

License:Open Source License

public static synchronized void buildConfig(String hibfile, String mapdir, Configuration cfg)
        throws HibernateException, IOException, Exception {
    Bundle hibbundle = Platform.getBundle("com.mg.jet.birt.report.data.oda.ejbql");

    //??     ?/* w  w w .ja  v a  2 s.  com*/
    File cfgDir = new File(mapdir);
    if (cfgDir != null) {
        if (cfgDir.isDirectory())
            cfg.addDirectory(cfgDir);
        else if (cfgDir.length() > 0)
            cfg.addJar(cfgDir);
    }

    URL hibfiles = FileLocator.find(hibbundle, new Path(CommonConstant.HIBERNATE_CLASSES), null);
    URL hibURL = FileLocator.resolve(hibfiles);
    File hibDirectory = new File(hibURL.getPath());

    // ?    ? ,  ? ?? ?  
    File[] files = hibDirectory.listFiles();
    if (files != null)
        for (int i = 0; i < files.length; i++) {
            if (!files[i].isDirectory() && files[i].getName().startsWith("mg.")
                    && files[i].getName().endsWith(".hbm.xml")) {
                cfg.addFile(files[i]);
            }
        }

    // ?  MBSA
    //      loadMBSADatawarehouse(cfg);
    File mbsaData = new File(hibURL.getPath().concat(CommonConstant.DATAWAREHOUSE));
    if (mbsaData.isFile())
        cfg.addJar(mbsaData);

    cfg.addDirectory(hibDirectory);

    File cfgFile = new File(hibfile);
    if (cfgFile != null && cfgFile.length() > 0) {
        cfg.configure(cfgFile);
    } else {
        File configFile = new File(hibURL.getPath() + CommonConstant.DATAWAREHOUSE_CFG_FILE);
        cfg.configure(configFile);
    }
    return;
}

From source file:edu.wustl.common.util.dbManager.GenerateSchema.java

License:BSD License

public static void main(String[] args) throws HibernateException, IOException, Exception {
    boolean isToPrintOnConsole = false;
    boolean isToExecuteOnDB = false;
    if (args.length != 0) {
        String arg = args[0];/*from  w w  w.  ja v a 2s  .c  o m*/
        if (arg.equalsIgnoreCase("true")) {
            isToPrintOnConsole = true;
            isToExecuteOnDB = true;
        }
        if (arg.equalsIgnoreCase("false")) {
            isToPrintOnConsole = false;
            isToExecuteOnDB = false;
        }
    }

    File file = new File("db.properties");
    BufferedInputStream stram = new BufferedInputStream(new FileInputStream(file));
    Properties p = new Properties();
    p.load(stram);
    stram.close();

    Configuration cfg = new Configuration();
    cfg.setProperties(p);
    cfg.addDirectory(new File("./src"));
    new SchemaExport(cfg).setOutputFile("query.sql").setDelimiter(";").create(isToPrintOnConsole,
            isToExecuteOnDB);
    //      if(isToExecuteOnDB)
    //         new GenerateUser();
}

From source file:it.doqui.index.ecmengine.business.personalization.hibernate.RoutingLocalSessionFactoryBean.java

License:Open Source License

protected SessionFactory buildSessionFactory() throws Exception {
    logger.debug("[RoutingLocalSessionFactoryBean::buildSessionFactory] BEGIN");
    SessionFactory sf = null;/*from   w  ww  .  j  av a 2  s  .c om*/

    // Create Configuration instance.
    Configuration config = newConfiguration();

    DataSource currentDataSource = getCurrentDataSource();
    logger.debug("[RoutingLocalSessionFactoryBean::buildSessionFactory] " + "Repository '"
            + RepositoryManager.getCurrentRepository() + "' -- Got currentDataSource: " + currentDataSource);

    if (currentDataSource == null) {
        throw new IllegalStateException("Null DataSource!");
    }

    // Make given DataSource available for SessionFactory configuration.
    logger.debug("[RoutingLocalSessionFactoryBean::buildSessionFactory] " + "Thread '"
            + Thread.currentThread().getName() + "' -- Setting DataSource for current thread: "
            + currentDataSource);
    CONFIG_TIME_DS_HOLDER.set(currentDataSource);

    if (this.jtaTransactionManager != null) {
        // Make Spring-provided JTA TransactionManager available.
        CONFIG_TIME_TM_HOLDER.set(this.jtaTransactionManager);
    }

    if (this.lobHandler != null) {
        // Make given LobHandler available for SessionFactory configuration.
        // Do early because because mapping resource might refer to custom types.
        CONFIG_TIME_LOB_HANDLER_HOLDER.set(this.lobHandler);
    }

    try {
        // Set connection release mode "on_close" as default.
        // This was the case for Hibernate 3.0; Hibernate 3.1 changed
        // it to "auto" (i.e. "after_statement" or "after_transaction").
        // However, for Spring's resource management (in particular for
        // HibernateTransactionManager), "on_close" is the better default.
        config.setProperty(Environment.RELEASE_CONNECTIONS, ConnectionReleaseMode.ON_CLOSE.toString());

        if (!isExposeTransactionAwareSessionFactory()) {
            // Not exposing a SessionFactory proxy with transaction-aware
            // getCurrentSession() method -> set Hibernate 3.1 CurrentSessionContext
            // implementation instead, providing the Spring-managed Session that way.
            // Can be overridden by a custom value for corresponding Hibernate property.
            config.setProperty(Environment.CURRENT_SESSION_CONTEXT_CLASS,
                    "org.springframework.orm.hibernate3.SpringSessionContext");
        }

        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 (int i = 0; i < this.typeDefinitions.length; i++) {
                TypeDefinitionBean typeDef = this.typeDefinitions[i];
                mappings.addTypeDef(typeDef.getTypeName(), typeDef.getTypeClass(), typeDef.getParameters());
            }
        }

        if (this.filterDefinitions != null) {
            // Register specified Hibernate FilterDefinitions.
            for (int i = 0; i < this.filterDefinitions.length; i++) {
                config.addFilterDefinition(this.filterDefinitions[i]);
            }
        }

        if (this.configLocations != null) {
            for (int i = 0; i < this.configLocations.length; i++) {
                // Load Hibernate configuration from given location.
                config.configure(this.configLocations[i].getURL());
            }
        }

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

        if (currentDataSource != null) {
            boolean actuallyTransactionAware = (this.useTransactionAwareDataSource
                    || currentDataSource instanceof TransactionAwareDataSourceProxy);
            // Set Spring-provided DataSource as Hibernate ConnectionProvider.
            config.setProperty(Environment.CONNECTION_PROVIDER,
                    actuallyTransactionAware ? TransactionAwareDataSourceConnectionProvider.class.getName()
                            : RoutingLocalDataSourceConnectionProvider.class.getName());
        }

        if (this.jtaTransactionManager != null) {
            // Set Spring-provided JTA TransactionManager as Hibernate property.
            config.setProperty(Environment.TRANSACTION_MANAGER_STRATEGY,
                    LocalTransactionManagerLookup.class.getName());
        }

        if (this.mappingLocations != null) {
            // Register given Hibernate mapping definitions, contained in resource files.
            for (int i = 0; i < this.mappingLocations.length; i++) {
                config.addInputStream(this.mappingLocations[i].getInputStream());
            }
        }

        if (this.cacheableMappingLocations != null) {
            // Register given cacheable Hibernate mapping definitions, read from the file system.
            for (int i = 0; i < this.cacheableMappingLocations.length; i++) {
                config.addCacheableFile(this.cacheableMappingLocations[i].getFile());
            }
        }

        if (this.mappingJarLocations != null) {
            // Register given Hibernate mapping definitions, contained in jar files.
            for (int i = 0; i < this.mappingJarLocations.length; i++) {
                Resource resource = this.mappingJarLocations[i];
                config.addJar(resource.getFile());
            }
        }

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

        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<?, ?> entry : this.eventListeners.entrySet()) {
                Assert.isTrue(entry.getKey() instanceof String,
                        "Event listener key needs to be of type String");
                String listenerType = (String) entry.getKey();
                Object listenerObject = entry.getValue();

                if (listenerObject instanceof Collection) {
                    Collection<?> listeners = (Collection<?>) 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.debug(
                "[RoutingLocalSessionFactoryBean::buildSessionFactory] Building new Hibernate SessionFactory.");
        this.configuration = config;

        SessionFactoryProxy sessionFactoryProxy = new SessionFactoryProxy(
                repositoryManager.getDefaultRepository().getId());
        for (Repository repository : repositoryManager.getRepositories()) {
            logger.debug("[RoutingLocalSessionFactoryBean::buildSessionFactory] " + "Repository '"
                    + repository.getId() + "' -- Building SessionFactory...");

            RepositoryManager.setCurrentRepository(repository.getId());
            sessionFactoryProxy.addSessionFactory(repository.getId(), newSessionFactory(config));
        }
        RepositoryManager.setCurrentRepository(repositoryManager.getDefaultRepository().getId());
        sf = sessionFactoryProxy;
    } finally {
        if (currentDataSource != null) {
            // Reset DataSource holder.
            CONFIG_TIME_DS_HOLDER.set(null);
        }

        if (this.jtaTransactionManager != null) {
            // Reset TransactionManager holder.
            CONFIG_TIME_TM_HOLDER.set(null);
        }

        if (this.lobHandler != null) {
            // Reset LobHandler holder.
            CONFIG_TIME_LOB_HANDLER_HOLDER.set(null);
        }
    }

    // Execute schema update if requested.
    if (this.schemaUpdate) {
        updateDatabaseSchema();
    }

    return sf;
}

From source file:mnzw.projekty.HiberUtil.java

public static SessionFactory getXMLSessionFactory() {
    try {//  w w w .  j  a  v a  2s  .  c  o m
        File mappingDir = new File("src\\mnzw\\projekty\\mapowanie");
        Configuration config = new Configuration().configure();

        config.setProperty("hibernate.show_sql", "false");
        config.addDirectory(mappingDir);

        StandardServiceRegistryBuilder registryBuilder = new StandardServiceRegistryBuilder();
        registryBuilder.applySettings(config.getProperties());
        ServiceRegistry serviceRegistry = registryBuilder.build();

        SessionFactory sf = config.buildSessionFactory(serviceRegistry);

        return (sf);
    } catch (Throwable ex) {

        System.err.println("Initial SessionFactory creation failed." + ex);
        throw new ExceptionInInitializerError(ex);
    }
}

From source file:org.jboss.hibernate.jmx.Hibernate.java

License:Open Source License

private void handleMappings(Configuration cfg) {
    //if scanForMappingsEnabled=true we dont want to add the xyz.har file
    //as scanForMappingsEnabled=true has already added it to archiveClasspathUrls
    if (harUrl != null && !scanForMappingsEnabled) {
        final File file = new File(harUrl.getFile());
        if (file.isDirectory()) {
            cfg.addDirectory(file);
        } else {//from   w  w w  .j  ava 2s.  c  om
            cfg.addJar(file);
        }
    }

    Iterator itr = archiveClasspathUrls.iterator();
    while (itr.hasNext()) {
        final File archive = (File) itr.next();
        log.debug("Passing archive [" + archive + "] to Hibernate Configration");
        cfg.addJar(archive);
    }

    itr = directoryClasspathUrls.iterator();
    while (itr.hasNext()) {
        final File directory = (File) itr.next();
        log.debug("Passing directory [" + directory + "] to Hibernate Configration");
        cfg.addDirectory(directory);
    }
}

From source file:org.n52.sos.ds.hibernate.SessionFactoryProvider.java

License:Open Source License

@SuppressWarnings("unchecked")
@Override/*from   www.  ja  v a  2s.c  o  m*/
protected Configuration getConfiguration(Properties properties) throws ConfigurationException {
    try {
        Configuration configuration = new Configuration().configure("/sos-hibernate.cfg.xml");
        if (properties.containsKey(HIBERNATE_RESOURCES)) {
            List<String> resources = (List<String>) properties.get(HIBERNATE_RESOURCES);
            for (String resource : resources) {
                configuration.addResource(resource);
            }
            properties.remove(HIBERNATE_RESOURCES);
        } else if (properties.containsKey(HIBERNATE_DIRECTORY)) {
            String directories = (String) properties.get(HIBERNATE_DIRECTORY);
            for (String directory : directories.split(PATH_SEPERATOR)) {
                File hibernateDir = new File(directory);
                if (!hibernateDir.exists()) {
                    // try to configure from classpath (relative path)
                    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
                    URL dirUrl = classLoader.getResource(directory);
                    if (dirUrl != null) {
                        try {
                            hibernateDir = new File(
                                    URLDecoder.decode(dirUrl.getPath(), Charset.defaultCharset().toString()));
                        } catch (UnsupportedEncodingException e) {
                            throw new ConfigurationException("Unable to encode directory URL " + dirUrl + "!");
                        }
                    }
                }
                if (!hibernateDir.exists()) {
                    throw new ConfigurationException("Hibernate directory " + directory + " doesn't exist!");
                }
                configuration.addDirectory(hibernateDir);
            }
        } else {
            // keep this as default/fallback
            configuration.addDirectory(new File(getClass().getResource(HIBERNATE_MAPPING_CORE_PATH).toURI()));
            configuration.addDirectory(
                    new File(getClass().getResource(HIBERNATE_MAPPING_TRANSACTIONAL_PATH).toURI()));
            configuration.addDirectory(new File(
                    getClass().getResource(HIBERNATE_MAPPING_SERIES_CONCEPT_OBSERVATION_PATH).toURI()));
        }
        return configuration;
    } catch (HibernateException he) {
        String exceptionText = "An error occurs during instantiation of the database connection pool!";
        LOGGER.error(exceptionText, he);
        cleanup();
        throw new ConfigurationException(exceptionText, he);
    } catch (URISyntaxException urise) {
        String exceptionText = "An error occurs during instantiation of the database connection pool!";
        LOGGER.error(exceptionText, urise);
        cleanup();
        throw new ConfigurationException(exceptionText, urise);
    }
}

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

License:Open Source License

private void setDirectoriesForModelSelection(int selection, boolean oldConcept, Configuration configuration)
        throws Exception {
    switch (selection) {
    case 1:/*ww w.ja  v  a  2s. com*/
        configuration.addDirectory(new File(SQLScriptGenerator.class.getResource("/mapping/core").toURI()));
        if (oldConcept) {
            configuration.addDirectory(
                    new File(SQLScriptGenerator.class.getResource("/mapping/old/observation").toURI()));
        } else {
            configuration.addDirectory(
                    new File(SQLScriptGenerator.class.getResource("/mapping/series/observation").toURI()));
        }
        break;
    case 2:
        configuration.addDirectory(new File(SQLScriptGenerator.class.getResource("/mapping/core").toURI()));
        if (oldConcept) {
            configuration.addDirectory(
                    new File(SQLScriptGenerator.class.getResource("/mapping/old/observation").toURI()));
        } else {
            configuration.addDirectory(
                    new File(SQLScriptGenerator.class.getResource("/mapping/series/observation").toURI()));
        }
        configuration
                .addDirectory(new File(SQLScriptGenerator.class.getResource("/mapping/transactional").toURI()));
        break;
    case 3:
        configuration.addDirectory(new File(SQLScriptGenerator.class.getResource("/mapping/core").toURI()));
        if (oldConcept) {
            configuration.addDirectory(
                    new File(SQLScriptGenerator.class.getResource("/mapping/old/observation").toURI()));
            configuration.addDirectory(new File(
                    SQLScriptGenerator.class.getResource("/mapping/old/spatialFilteringProfile").toURI()));
        } else {
            configuration.addDirectory(
                    new File(SQLScriptGenerator.class.getResource("/mapping/series/observation").toURI()));
            configuration.addDirectory(new File(
                    SQLScriptGenerator.class.getResource("/mapping/series/spatialFilteringProfile").toURI()));
        }
        break;
    case 4:
        configuration.addDirectory(new File(SQLScriptGenerator.class.getResource("/mapping/core").toURI()));
        configuration
                .addDirectory(new File(SQLScriptGenerator.class.getResource("/mapping/transactional").toURI()));
        if (oldConcept) {
            configuration.addDirectory(
                    new File(SQLScriptGenerator.class.getResource("/mapping/old/observation").toURI()));
            configuration.addDirectory(new File(
                    SQLScriptGenerator.class.getResource("/mapping/old/spatialFilteringProfile").toURI()));
        } else {
            configuration.addDirectory(
                    new File(SQLScriptGenerator.class.getResource("/mapping/series/observation").toURI()));
            configuration.addDirectory(new File(
                    SQLScriptGenerator.class.getResource("/mapping/series/spatialFilteringProfile").toURI()));
        }
        break;
    case 5:
        configuration.addDirectory(new File(SQLScriptGenerator.class.getResource("/mapping/core").toURI()));
        configuration
                .addDirectory(new File(SQLScriptGenerator.class.getResource("/mapping/transactional").toURI()));
        configuration.addDirectory(new File(SQLScriptGenerator.class.getResource("/mapping/i18n").toURI()));
        if (oldConcept) {
            configuration.addDirectory(
                    new File(SQLScriptGenerator.class.getResource("/mapping/old/observation").toURI()));
            configuration.addDirectory(new File(
                    SQLScriptGenerator.class.getResource("/mapping/old/spatialFilteringProfile").toURI()));
        } else {
            configuration.addDirectory(
                    new File(SQLScriptGenerator.class.getResource("/mapping/series/observation").toURI()));
            configuration.addDirectory(new File(
                    SQLScriptGenerator.class.getResource("/mapping/series/spatialFilteringProfile").toURI()));
        }
        break;
    default:
        throw new Exception("The entered value is invalid!");
    }
}

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  a  2  s .  c om
    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);
        }
    }
}