Java Code Examples for org.hibernate.Session#disconnect()

The following examples show how to use org.hibernate.Session#disconnect() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SessionSynchronization.java    From micronaut-data with Apache License 2.0 6 votes vote down vote up
@Override
@SuppressWarnings("deprecation")
public void beforeCompletion() {
    try {
        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;
        }
    }
}
 
Example 2
Source File: SpringSessionSynchronization.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Override
@SuppressWarnings("deprecation")
public void beforeCompletion() {
	try {
		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;
		}
	}
}
 
Example 3
Source File: ConnectionManagementTestCase.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Test that the legacy manual disconnect()/reconnect() chain works as
 * expected in the given environment.
 *
 * @throws Throwable
 */
public final void testManualDisconnectChain() throws Throwable {
	prepare();
	Session sessionUnderTest = getSessionUnderTest();

	sessionUnderTest.disconnect();

	byte[] bytes = SerializationHelper.serialize( sessionUnderTest );
	checkSerializedState( sessionUnderTest );
	Session s2 = ( Session ) SerializationHelper.deserialize( bytes );
	checkDeserializedState( s2 );

	reconnect( s2 );

	s2.disconnect();
	reconnect( s2 );

	release( sessionUnderTest );
	release( s2 );
	done();
}
 
Example 4
Source File: SpringSessionSynchronization.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void beforeCompletion() {
	try {
		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;
		}
	}
}
 
Example 5
Source File: SpringSessionSynchronization.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
@SuppressWarnings("deprecation")
public void beforeCompletion() {
	try {
		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;
		}
	}
}
 
Example 6
Source File: SpringSessionSynchronization.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Override
public void beforeCompletion() {
	try {
		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;
		}
	}
}
 
Example 7
Source File: SpringSessionSynchronization.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Override
@SuppressWarnings("deprecation")
public void beforeCompletion() {
	try {
		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;
		}
	}
}
 
Example 8
Source File: SpringSessionSynchronization.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Override
public void beforeCompletion() {
	try {
		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;
		}
	}
}
 
Example 9
Source File: ConnectionManagementTestCase.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Test that the legacy manual disconnect()/reconnect() chain works as
 * expected in the given environment.  Similiar to {@link #testManualDisconnectChain}
 * expect that here we force the session to acquire and hold JDBC resources
 * prior to disconnecting.
 *
 * @throws Throwable
 */
public final void testManualDisconnectWithOpenResources() throws Throwable {
	prepare();
	Session sessionUnderTest = getSessionUnderTest();

	Silly silly = new Silly( "tester" );
	sessionUnderTest.save( silly );
	sessionUnderTest.flush();

	sessionUnderTest.createQuery( "from Silly" ).iterate();

	sessionUnderTest.disconnect();
	SerializationHelper.serialize( sessionUnderTest );
	checkSerializedState( sessionUnderTest );

	reconnect( sessionUnderTest );
	sessionUnderTest.createQuery( "from Silly" ).scroll();

	sessionUnderTest.disconnect();
	SerializationHelper.serialize( sessionUnderTest );
	checkSerializedState( sessionUnderTest );

	reconnect( sessionUnderTest );
	sessionUnderTest.delete( silly );
	sessionUnderTest.flush();

	release( sessionUnderTest );
	done();
}
 
Example 10
Source File: ConnectionManagementTestCase.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Test that a session which has been manually disconnected will be allowed
 * to serialize.
 *
 * @throws Throwable
 */
public final void testManualDisconnectedSerialization() throws Throwable {
	prepare();
	Session sessionUnderTest = getSessionUnderTest();

	sessionUnderTest.disconnect();

	SerializationHelper.serialize( sessionUnderTest );
	checkSerializedState( sessionUnderTest );

	release( sessionUnderTest );
	done();
}
 
Example 11
Source File: SpringSessionSynchronization.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void afterCompletion(int status) {
	try {
		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);
		}
	}
}
 
Example 12
Source File: SpringSessionSynchronization.java    From lemon with Apache License 2.0 5 votes vote down vote up
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());
    }

    // Eagerly disconnect the Session here, to make release mode "on_close" work nicely.
    session.disconnect();
}
 
Example 13
Source File: HibernateDao.java    From DataHubSystem with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * <p>Returns a List of <b>T</b> entities, where HQL clauses can be
 * specified.</p>
 * 
 * Note: This method is useful in read only. It can be use to delete or 
 * create <b>T</b> entities, but caution with <code>top</code> and 
 * <code>skip</code> arguments.
 * 
 * @param clauses query clauses (WHERE, ORDER BY, GROUP BY), if null no
 * clauses are apply.
 * @param skip number of entities to skip.
 * @param n  number of entities max returned.
 * @return a list of <b>T</b> entities.
 */
@SuppressWarnings ("unchecked")
public List<T> scroll (final String clauses, final int skip, final int n)
{
   StringBuilder hql = new StringBuilder ();
   hql.append ("FROM ").append (entityClass.getName ());
   if (clauses != null)
      hql.append (" ").append (clauses);

   Session session;
   boolean newSession = false;
   try
   {
      session = getSessionFactory ().getCurrentSession ();
   }
   catch (HibernateException e)
   {
      session = getSessionFactory ().openSession ();
      newSession = true;
   }

   Query query = session.createQuery (hql.toString ());
   if (skip > 0) query.setFirstResult (skip);
   if (n > 0) 
   {
      query.setMaxResults (n);
      query.setFetchSize (n);
   }
   
   logger.info("Execution of HQL: " + hql.toString ());
   long start = System.currentTimeMillis ();

   List<T> result = (List<T>) query.list ();
   logger.info("HQL executed in " + 
      (System.currentTimeMillis() -start) + "ms.");

   if (newSession)
   {
      session.disconnect ();
   }

   return result;
}
 
Example 14
Source File: HibernateTransactionManager.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
@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());
	}

	// 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();
}
 
Example 15
Source File: HibernateTransactionManager.java    From spring4-understanding with Apache License 2.0 2 votes vote down vote up
/**
 * 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.2
 * @see Session#disconnect()
 */
protected void disconnectOnCompletion(Session session) {
	session.disconnect();
}
 
Example 16
Source File: HibernateTransactionManager.java    From lams with GNU General Public License v2.0 2 votes vote down vote up
/**
 * 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
 * @see Session#disconnect()
 */
protected void disconnectOnCompletion(Session session) {
	session.disconnect();
}
 
Example 17
Source File: HibernateTransactionManager.java    From spring4-understanding with Apache License 2.0 2 votes vote down vote up
/**
 * 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
 * @see org.hibernate.Session#disconnect()
 */
protected void disconnectOnCompletion(Session session) {
	session.disconnect();
}
 
Example 18
Source File: HibernateTransactionManager.java    From lams with GNU General Public License v2.0 2 votes vote down vote up
/**
 * 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
 * @see org.hibernate.Session#disconnect()
 */
protected void disconnectOnCompletion(Session session) {
	session.disconnect();
}
 
Example 19
Source File: HibernateTransactionManager.java    From java-technology-stack with MIT License 2 votes vote down vote up
/**
 * 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
 * @see Session#disconnect()
 */
protected void disconnectOnCompletion(Session session) {
	session.disconnect();
}
 
Example 20
Source File: HibernateTransactionManager.java    From spring-analysis-note with MIT License 2 votes vote down vote up
/**
 * 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
 * @see Session#disconnect()
 */
protected void disconnectOnCompletion(Session session) {
	session.disconnect();
}