Example usage for org.hibernate.cfg Configuration addJar

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

Introduction

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

Prototype

public Configuration addJar(File jar) throws MappingException 

Source Link

Document

Read all mappings from a jar file

Assumes that any file named *.hbm.xml is a mapping document.

Usage

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);
    }/*from   ww  w. j  av  a 2  s .c om*/
    // 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  ww.j av  a  2 s. co m*/
    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: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  a2 s. c  o m*/

    // 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:it.eng.qbe.datasource.hibernate.HibernateDataSource.java

License:Mozilla Public License

protected void addDatamart(FileDataSourceConfiguration configuration, boolean extendClassLoader) {
    Configuration cfg = null;
    SessionFactory sf = null;/*from  w w w .j  a  v a 2  s . com*/

    if (configuration.getFile() == null)
        return;

    cfg = buildEmptyConfiguration();
    configurationMap.put(configuration.getModelName(), cfg);

    if (extendClassLoader) {
        updateCurrentClassLoader(configuration.getFile());
    }

    cfg.addJar(configuration.getFile());

    try {
        compositeHibernateConfiguration.addJar(configuration.getFile());
    } catch (Throwable t) {
        throw new RuntimeException("Cannot add datamart", t);
    }

    sf = cfg.buildSessionFactory();
    sessionFactoryMap.put(configuration.getModelName(), sf);
}

From source file:it.eng.qbe.datasource.hibernate.HibernateDataSourceWithClassLoader.java

License:Mozilla Public License

@Override
protected void addDatamart(FileDataSourceConfiguration configuration, boolean extendClassLoader) {
    Configuration cfg = null;
    SessionFactory sf = null;//w  ww  . j a v a2  s  .c  o  m
    if (configuration.getFile() == null)
        return;

    cfg = buildEmptyConfiguration();
    configurationMap.put(configuration.getModelName(), cfg);

    if (extendClassLoader) {
        myClassLoader = ClassLoaderManager.updateCurrentClassLoader(configuration.getFile());
    }

    cfg.addJar(configuration.getFile());

    try {
        compositeHibernateConfiguration.addJar(configuration.getFile());
    } catch (Throwable t) {
        throw new RuntimeException("Cannot add datamart", t);
    }

    sf = cfg.buildSessionFactory();
    sessionFactoryMap.put(configuration.getModelName(), sf);
}

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);//from ww  w  .ja va2s.c  om
        } else {
            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.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:sk.cagani.stuba.bpbp.serverApp.DatabaseConnector.java

public DatabaseConnector() {
    Configuration configuration = new Configuration();
    configuration.configure("hibernate.cfg.xml");
    configuration.addJar(new File("/home/debian/BPbp/target/lib/BPbpDatabaseMapper-1.0.jar"));
    StandardServiceRegistryBuilder ssrb = new StandardServiceRegistryBuilder()
            .applySettings(configuration.getProperties());
    sessionFactory = configuration.buildSessionFactory(ssrb.build());
    stats = sessionFactory.getStatistics();
    stats.setStatisticsEnabled(true);/*from  w w  w. j av  a  2  s  .  c o m*/
}