Example usage for org.hibernate ConnectionReleaseMode ON_CLOSE

List of usage examples for org.hibernate ConnectionReleaseMode ON_CLOSE

Introduction

In this page you can find the example usage for org.hibernate ConnectionReleaseMode ON_CLOSE.

Prototype

ConnectionReleaseMode ON_CLOSE

To view the source code for org.hibernate ConnectionReleaseMode ON_CLOSE.

Click Source Link

Document

Indicates that connections should only be released when the Session is explicitly closed or disconnected; this is the legacy (Hibernate2 and pre-3.1) behavior.

Usage

From source file:com.byteslounge.spring.tx.MyOwnTxManager.java

License:Apache License

/**
 * Return whether the given Hibernate Session will always hold the same
 * JDBC Connection. This is used to check whether the transaction manager
 * can safely prepare and clean up the JDBC Connection used for a transaction.
 * <p>The default implementation checks the Session's connection release mode
 * to be "on_close".//from   w w  w .  j a  v a  2  s .  c om
 * @param session the Hibernate Session to check
 * @see org.hibernate.engine.transaction.spi.TransactionContext#getConnectionReleaseMode()
 * @see org.hibernate.ConnectionReleaseMode#ON_CLOSE
 */
protected boolean isSameConnectionForEntireSession(Session session) {
    if (!(session instanceof TransactionContext)) {
        // The best we can do is to assume we're safe.
        return true;
    }
    ConnectionReleaseMode releaseMode = ((TransactionContext) session).getConnectionReleaseMode();
    return ConnectionReleaseMode.ON_CLOSE.equals(releaseMode);
}

From source file:com.redhat.rhn.common.hibernate.NestedTransactionFactory.java

License:Open Source License

/** {@inheritDoc} */
public ConnectionReleaseMode getDefaultReleaseMode() {
    // match the default 3.1 behavior, in our case
    // this is at the end of the request.
    return ConnectionReleaseMode.ON_CLOSE;
}

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  w w . j  a v a2s  .co 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:kr.debop4j.data.hibernate.spring.HibernateConfigBase.java

License:Apache License

/** Hibernate   */
protected Properties hibernateProperties() {

    Properties props = new Properties();

    props.put(Environment.FORMAT_SQL, "true");
    props.put(Environment.HBM2DDL_AUTO, "create"); // create | spawn | spawn-drop | update | validate | none

    props.put(Environment.SHOW_SQL, "true");
    props.put(Environment.RELEASE_CONNECTIONS, ConnectionReleaseMode.ON_CLOSE);
    props.put(Environment.AUTOCOMMIT, "true");
    props.put(Environment.STATEMENT_BATCH_SIZE, "30");

    return props;
}

From source file:kr.debop4j.search.AppConfig.java

License:Apache License

protected Properties hibernateProperties() {

    Properties props = new Properties();

    props.put(Environment.DIALECT, "org.hibernate.dialect.HSQLDialect");

    props.put(Environment.FORMAT_SQL, "true");
    props.put(Environment.HBM2DDL_AUTO, "create"); // create | spawn | spawn-drop | update | validate
    props.put(Environment.SHOW_SQL, "true");
    props.put(Environment.RELEASE_CONNECTIONS, ConnectionReleaseMode.ON_CLOSE);
    props.put(Environment.AUTOCOMMIT, "true");
    props.put(Environment.CURRENT_SESSION_CONTEXT_CLASS, "thread");
    props.put(Environment.STATEMENT_BATCH_SIZE, "50");

    // hibernate-search 
    props.put("hibernate.search.lucene_version", "LUCENE_36");
    // props.put("hibernate.search.default.indexmanager", "near-real-time");
    props.put("hibernate.search.default.directory_provider", "filesystem");
    props.put("hibernate.search.default.indexBase", ".lucene/indexes");

    // hibernate-search sharding
    //        String defaultPrefix = "hibernate.search.default";
    //        props.put(defaultPrefix + ".sharding_strategy.nbr_of_shards", Integer.toString(Runtime.getRuntime().availableProcessors()));
    //        props.put(defaultPrefix + ".directory_provider", FSDirectoryProvider.class.getName());

    // hibernate-search performance settings
    // props.put("hibernate.search.worker.execution", "async");
    props.put("hibernate.search.worker.thread_pool.size", "8");
    props.put("hibernate.search.worker.buffer_queue.max", "1000");
    props.put("hibernate.search.default.indexwriter.max_buffered_doc", "true");
    props.put("hibernate.search.default.indexwriter.max_merge_docs", "100");
    props.put("hibernate.search.default.indexwriter.merge_factor", "20");
    props.put("hibernate.search.default.indexwriter.term_index_interval", "default");
    props.put("hibernate.search.default.indexwriter.ram_buffer_size", "1024");

    ///*ww w  . j  a  va 2  s. com*/
    props.put("hibernate.search.default.exclusive_index_use", "true");

    // Validator
    props.put("javax.persistencexml.validation.group.pre-persist", "javax.validation.groups.Default");
    props.put("javax.persistencexml.validation.group.pre-update", "javax.validation.groups.Default");

    return props;
}

From source file:org.beangle.commons.orm.hibernate.BeangleTransactionFactory.java

License:Open Source License

/**
 * Sets connection release mode "on_close" as default.
 * <p>/* w  ww  .  ja  v a 2  s .com*/
 * 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.
 */
public ConnectionReleaseMode getDefaultReleaseMode() {
    return ConnectionReleaseMode.ON_CLOSE;
}

From source file:org.beangle.commons.orm.hibernate.HibernateTransactionManager.java

License:Open Source License

/**
 * Return whether the given Hibernate Session will always hold the same
 * JDBC Connection. This is used to check whether the transaction manager
 * can safely prepare and clean up the JDBC Connection used for a transaction.
 * <p>/*from w  ww .  j  a  v a 2s . c o  m*/
 * Default implementation checks the Session's connection release mode to be "on_close".
 * Unfortunately, this requires casting to SessionImpl, as of Hibernate 3.1. If that cast doesn't
 * work, we'll simply assume we're safe and return <code>true</code>.
 * 
 * @param session the Hibernate Session to check
 * @see org.hibernate.impl.SessionImpl#getConnectionReleaseMode()
 * @see org.hibernate.ConnectionReleaseMode#ON_CLOSE
 */
protected boolean isSameConnectionForEntireSession(Session session) {
    if (!(session instanceof SessionImpl)) {
        // The best we can do is to assume we're safe.
        return true;
    }
    ConnectionReleaseMode releaseMode = ((SessionImpl) session).getConnectionReleaseMode();
    return ConnectionReleaseMode.ON_CLOSE.equals(releaseMode);
}

From source file:org.beangle.orm.hibernate.HibernateTransactionManager.java

License:Open Source License

/**
 * Return whether the given Hibernate Session will always hold the same
 * JDBC Connection. This is used to check whether the transaction manager
 * can safely prepare and clean up the JDBC Connection used for a transaction.
 * <p>/*from w  w  w .j  av a2s .c  o  m*/
 * Default implementation checks the Session's connection release mode to be "on_close".
 * Unfortunately, this requires casting to SessionImpl, as of Hibernate 3.1. If that cast doesn't
 * work, we'll simply assume we're safe and return <code>true</code>.
 * 
 * @param session the Hibernate Session to check
 * @see org.hibernate.impl.SessionImpl#getConnectionReleaseMode()
 * @see org.hibernate.ConnectionReleaseMode#ON_CLOSE
 */
protected boolean isSameConnectionForEntireSession(Session session) {
    // The best we can do is to assume we're safe.
    if (!(session instanceof TransactionContext))
        return true;
    ConnectionReleaseMode releaseMode = ((TransactionContext) session).getConnectionReleaseMode();
    return ConnectionReleaseMode.ON_CLOSE.equals(releaseMode);
}

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

License:Apache License

/**
 * Sets connection release mode "on_close" as default.
 * <p>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.
 *//*from  ww  w  . ja  v  a 2s .  c o  m*/
@Override
public ConnectionReleaseMode getDefaultReleaseMode() {
    return ConnectionReleaseMode.ON_CLOSE;
}

From source file:org.springframework.orm.hibernate5.HibernateTransactionManager.java

License:Apache License

/**
 * Return whether the given Hibernate Session will always hold the same
 * JDBC Connection. This is used to check whether the transaction manager
 * can safely prepare and clean up the JDBC Connection used for a transaction.
 * <p>The default implementation checks the Session's connection release mode
 * to be "on_close"./*  w  ww .  j  av  a2s .c o m*/
 * @param session the Hibernate Session to check
 * @see ConnectionReleaseMode#ON_CLOSE
 */
protected boolean isSameConnectionForEntireSession(Session session) {
    if (!(session instanceof SessionImplementor)) {
        // The best we can do is to assume we're safe.
        return true;
    }
    ConnectionReleaseMode releaseMode = ((SessionImplementor) session).getJdbcCoordinator()
            .getConnectionReleaseMode();
    return ConnectionReleaseMode.ON_CLOSE.equals(releaseMode);
}