Example usage for org.hibernate Session disconnect

List of usage examples for org.hibernate Session disconnect

Introduction

In this page you can find the example usage for org.hibernate Session disconnect.

Prototype

Connection disconnect();

Source Link

Document

Disconnect the session from its underlying JDBC connection.

Usage

From source file:org.projectforge.framework.persistence.history.HibernateSearchDependentObjectsReindexer.java

License:Open Source License

public void reindexDependents(final BaseDO<?> obj) {
    new Thread() {
        @Override/*from w ww .j a v a  2 s .  c  o  m*/
        public void run() {
            final Session session = applicationContext.getBean(HibernateTemplate.class).getSessionFactory()
                    .openSession();
            final Set<String> alreadyReindexed = new HashSet<String>();
            final List<Entry> entryList = map.get(obj.getClass());
            reindexDependents(session, obj, entryList, alreadyReindexed);
            session.disconnect();
            final int size = alreadyReindexed.size();
            if (size >= 10) {
                log.info("Re-indexing of " + size + " objects done after updating " + obj.getClass().getName()
                        + ":" + obj.getId());
            }
        }
    }.start();
}

From source file:org.sapia.soto.hibernate.SessionState.java

License:Open Source License

/**
 * Unregisters the session that is associated to the calling thread.
 *
 * @param close if <code>true</code>, this method internally closes the
 * session.//from  www.ja  va 2s  .  c o  m
 * 
 * @deprecated use one of the unjoin() methods.
 * 
 * @see #unjoin()
 * @see #unjoinAndClose()
 */
public static void unregister(boolean close) {
    Session s = (Session) _sessionRef.get();
    if (s != null) {
        if (close) {
            if (s.isOpen()) {
                s.close();
            }
        } else {
            if (s.isConnected()) {
                s.disconnect();
            }
        }
        _sessionRef.set(null);
    }
}

From source file:org.sapia.soto.hibernate.SessionState.java

License:Open Source License

/**
 * Calls the <code>disconnect()</code> method on the session that is 
 * currently registered with the calling thread - also unregisters that
 * session from it.//  w ww .  j a  v a2s .  c o m
 */
public static void disconnect() {
    Session session = (Session) _sessionRef.get();
    if (session != null && session.isConnected()) {
        session.disconnect();
        _sessionRef.set(null);
    }
}

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

License:Apache License

@Override
@SuppressWarnings("deprecation")
protected void doCleanupAfterCompletion(Object transaction) {
    HibernateTransactionObject txObject = (HibernateTransactionObject) transaction;

    // Remove the session holder from the thread.
    if (txObject.isNewSessionHolder()) {
        TransactionSynchronizationManager.unbindResource(getSessionFactory());
    }// w w w . j  av  a  2 s. co  m

    // Remove the JDBC connection holder from the thread, if exposed.
    if (getDataSource() != null) {
        TransactionSynchronizationManager.unbindResource(getDataSource());
    }

    Session session = txObject.getSessionHolder().getSession();
    if (this.prepareConnection && session.isConnected() && isSameConnectionForEntireSession(session)) {
        // We're running with connection release mode "on_close": We're able to reset
        // the isolation level and/or read-only flag of the JDBC Connection here.
        // Else, we need to rely on the connection pool to perform proper cleanup.
        try {
            Connection con = session.connection();
            DataSourceUtils.resetConnectionAfterTransaction(con, txObject.getPreviousIsolationLevel());
        } catch (HibernateException ex) {
            logger.debug("Could not access JDBC Connection of Hibernate Session", ex);
        }
    }

    if (txObject.isNewSession()) {
        if (logger.isDebugEnabled()) {
            logger.debug("Closing Hibernate Session [" + SessionFactoryUtils.toString(session)
                    + "] after transaction");
        }
        SessionFactoryUtils.closeSessionOrRegisterDeferredClose(session, getSessionFactory());
    } else {
        if (logger.isDebugEnabled()) {
            logger.debug("Not closing pre-bound Hibernate Session [" + SessionFactoryUtils.toString(session)
                    + "] after transaction");
        }
        if (txObject.getSessionHolder().getPreviousFlushMode() != null) {
            session.setFlushMode(txObject.getSessionHolder().getPreviousFlushMode());
        }
        if (!this.hibernateManagedSession) {
            session.disconnect();
        }
    }
    txObject.getSessionHolder().clear();
}

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

License:Apache License

@Override
public void beforeCompletion() {
    if (this.jtaTransaction != null) {
        // Typically in case of a suspended JTA transaction:
        // Remove the Session for the current JTA transaction, but keep the holder.
        Session session = this.sessionHolder.removeSession(this.jtaTransaction);
        if (session != null) {
            if (this.sessionHolder.isEmpty()) {
                // No Sessions for JTA transactions bound anymore -> could remove it.
                TransactionSynchronizationManager.unbindResourceIfPossible(this.sessionFactory);
                this.holderActive = false;
            }/*from   w  w w.  j a  v  a2s .c  o m*/
            // Do not close a pre-bound Session. In that case, we'll find the
            // transaction-specific Session the same as the default Session.
            if (session != this.sessionHolder.getSession()) {
                SessionFactoryUtils.closeSessionOrRegisterDeferredClose(session, this.sessionFactory);
            } else {
                if (this.sessionHolder.getPreviousFlushMode() != null) {
                    // In case of pre-bound Session, restore previous flush mode.
                    session.setFlushMode(this.sessionHolder.getPreviousFlushMode());
                }
                // Eagerly disconnect the Session here, to make release mode "on_close" work nicely.
                session.disconnect();
            }
            return;
        }
    }
    // We'll only get here if there was no specific JTA transaction to handle.
    if (this.newSession) {
        // Default behavior: unbind and close the thread-bound Hibernate Session.
        TransactionSynchronizationManager.unbindResource(this.sessionFactory);
        this.holderActive = false;
        if (this.hibernateTransactionCompletion) {
            // Close the Hibernate Session here in case of a Hibernate TransactionManagerLookup:
            // Hibernate will automatically defer the actual closing until JTA transaction completion.
            // Else, the Session will be closed in the afterCompletion method, to provide the
            // correct transaction status for releasing the Session's cache locks.
            SessionFactoryUtils.closeSessionOrRegisterDeferredClose(this.sessionHolder.getSession(),
                    this.sessionFactory);
        }
    } else {
        Session session = this.sessionHolder.getSession();
        if (this.sessionHolder.getPreviousFlushMode() != null) {
            // In case of pre-bound Session, restore previous flush mode.
            session.setFlushMode(this.sessionHolder.getPreviousFlushMode());
        }
        if (this.hibernateTransactionCompletion) {
            // Eagerly disconnect the Session here, to make release mode "on_close" work nicely.
            // We know that this is appropriate if a TransactionManagerLookup has been specified.
            session.disconnect();
        }
    }
}

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

License:Apache License

@Override
public void afterCompletion(int status) {
    try {//from  www  .  ja va2  s  . com
        if (!this.hibernateTransactionCompletion || !this.newSession) {
            // No Hibernate TransactionManagerLookup: apply afterTransactionCompletion callback.
            // Always perform explicit afterTransactionCompletion callback for pre-bound Session,
            // even with Hibernate TransactionManagerLookup (which only applies to new Sessions).
            Session session = this.sessionHolder.getSession();
            // Provide correct transaction status for releasing the Session's cache locks,
            // if possible. Else, closing will release all cache locks assuming a rollback.
            try {
                if (session instanceof SessionImplementor) {
                    ((SessionImplementor) session).afterTransactionCompletion(status == STATUS_COMMITTED, null);
                }
            } finally {
                // Close the Hibernate Session here if necessary
                // (closed in beforeCompletion in case of TransactionManagerLookup).
                if (this.newSession) {
                    SessionFactoryUtils.closeSessionOrRegisterDeferredClose(session, this.sessionFactory);
                } else if (!this.hibernateTransactionCompletion) {
                    session.disconnect();
                }
            }
        }
        if (!this.newSession && status != STATUS_COMMITTED) {
            // Clear all pending inserts/updates/deletes in the Session.
            // Necessary for pre-bound Sessions, to avoid inconsistent state.
            this.sessionHolder.getSession().clear();
        }
    } finally {
        if (this.sessionHolder.doesNotHoldNonDefaultSession()) {
            this.sessionHolder.setSynchronizedWithTransaction(false);
        }
    }
}

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

License:Apache License

/**
 * Disconnect a pre-existing Hibernate Session on transaction completion,
 * returning its database connection but preserving its entity state.
 * <p>The default implementation simply calls {@link Session#disconnect()}.
 * Subclasses may override this with a no-op or with fine-tuned disconnection logic.
 * @param session the Hibernate Session to disconnect
 * @since 4.1.2//from w  w w . j  ava 2 s  . c  om
 * @see org.hibernate.Session#disconnect()
 */
protected void disconnectOnCompletion(Session session) {
    session.disconnect();
}

From source file:org.springframework.orm.hibernate4.SpringSessionSynchronization.java

License:Apache License

@Override
public void beforeCompletion() {
    Session session = this.sessionHolder.getSession();
    if (this.sessionHolder.getPreviousFlushMode() != null) {
        // In case of pre-bound Session, restore previous flush mode.
        session.setFlushMode(this.sessionHolder.getPreviousFlushMode());
    }//from   w  ww .j a  v a  2 s  .  com
    // Eagerly disconnect the Session here, to make release mode "on_close" work nicely.
    session.disconnect();

    // Unbind at this point if it's a new Session...
    if (this.newSession) {
        TransactionSynchronizationManager.unbindResource(this.sessionFactory);
        this.holderActive = false;
    }
}

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

License:Apache License

@Override
public void beforeCompletion() {
    try {/*  w w  w . j  a va  2 s .c o  m*/
        Session session = this.sessionHolder.getSession();
        if (this.sessionHolder.getPreviousFlushMode() != null) {
            // In case of pre-bound Session, restore previous flush mode.
            session.setFlushMode(this.sessionHolder.getPreviousFlushMode());
        }
        // Eagerly disconnect the Session here, to make release mode "on_close" work nicely.
        session.disconnect();
    } finally {
        // Unbind at this point if it's a new Session...
        if (this.newSession) {
            TransactionSynchronizationManager.unbindResource(this.sessionFactory);
            this.holderActive = false;
        }
    }
}

From source file:us.opulo.p.hibernate.SessionManager.java

License:Open Source License

/**
 * Closes the session for the current thread.
 * @throws IllegalStateException Thrown if the session is already closed. 
 *//*  ww w  .  j  av  a 2  s .c  o m*/
public static synchronized final void close() {
    Session session = ACTIVE_SESSIONS.get();

    if (session == null) {
        throw new IllegalStateException(INVALID_SESSION);
    }

    if (session.isConnected()) {
        session.flush();
        session.disconnect();
        session.close();
        ACTIVE_SESSIONS.remove();
        log.debug("Session closed");
    }
}