Java Code Examples for org.hibernate.Session.setFlushMode()

The following are Jave code examples for showing how to use setFlushMode() of the org.hibernate.Session class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: lams   File: HibernateJpaDialect.java   Source Code and License Vote up 6 votes
@Override
public Object prepareTransaction(EntityManager entityManager, boolean readOnly, String name)
		throws PersistenceException {

	Session session = getSession(entityManager);
	FlushMode flushMode = session.getFlushMode();
	FlushMode previousFlushMode = null;
	if (readOnly) {
		// We should suppress flushing for a read-only transaction.
		session.setFlushMode(FlushMode.MANUAL);
		previousFlushMode = flushMode;
	}
	else {
		// We need AUTO or COMMIT for a non-read-only transaction.
		if (flushMode.lessThan(FlushMode.COMMIT)) {
			session.setFlushMode(FlushMode.AUTO);
			previousFlushMode = flushMode;
		}
	}
	return new SessionTransactionData(session, previousFlushMode);
}
 
Example 2
Project: lams   File: HibernateTransactionManager.java   Source Code and License Vote up 6 votes
@Override
protected void prepareForCommit(DefaultTransactionStatus status) {
	if (this.earlyFlushBeforeCommit && status.isNewTransaction()) {
		HibernateTransactionObject txObject = (HibernateTransactionObject) status.getTransaction();
		Session session = txObject.getSessionHolder().getSession();
		if (!session.getFlushMode().lessThan(FlushMode.COMMIT)) {
			logger.debug("Performing an early flush for Hibernate transaction");
			try {
				session.flush();
			}
			catch (HibernateException ex) {
				throw convertHibernateAccessException(ex);
			}
			finally {
				session.setFlushMode(FlushMode.MANUAL);
			}
		}
	}
}
 
Example 3
Project: lemon   File: SpringSessionContext.java   Source Code and License Vote up 5 votes
public Session currentSession() throws HibernateException {
    Object value = TransactionSynchronizationManager
            .getResource(this.sessionFactory);

    if (value instanceof Session) {
        return (Session) value;
    } else if (value instanceof SessionHolder) {
        SessionHolder sessionHolder = (SessionHolder) value;
        Session session = sessionHolder.getSession();

        if (TransactionSynchronizationManager.isSynchronizationActive()
                && !sessionHolder.isSynchronizedWithTransaction()) {
            TransactionSynchronizationManager
                    .registerSynchronization(new SpringSessionSynchronization(
                            sessionHolder, this.sessionFactory));
            sessionHolder.setSynchronizedWithTransaction(true);

            // Switch to FlushMode.AUTO, as we have to assume a thread-bound Session
            // with FlushMode.MANUAL, which needs to allow flushing within the transaction.
            FlushMode flushMode = session.getFlushMode();

            if (FlushMode.isManualFlushMode(flushMode)
                    && !TransactionSynchronizationManager
                            .isCurrentTransactionReadOnly()) {
                session.setFlushMode(FlushMode.AUTO);
                sessionHolder.setPreviousFlushMode(flushMode);
            }
        }

        return session;
    } else {
        throw new HibernateException("No Session found for current thread");
    }
}
 
Example 4
Project: lemon   File: SpringSessionSynchronization.java   Source Code and License Vote up 5 votes
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 5
Project: lams   File: OpenSessionInterceptor.java   Source Code and License Vote up 5 votes
/**
 * Open a Session for the SessionFactory that this interceptor uses.
 * <p>The default implementation delegates to the {@link SessionFactory#openSession}
 * method and sets the {@link Session}'s flush mode to "MANUAL".
 * @return the Session to use
 * @throws DataAccessResourceFailureException if the Session could not be created
 * @see org.hibernate.FlushMode#MANUAL
 */
protected Session openSession() throws DataAccessResourceFailureException {
	try {
		Session session = getSessionFactory().openSession();
		session.setFlushMode(FlushMode.MANUAL);
		return session;
	}
	catch (HibernateException ex) {
		throw new DataAccessResourceFailureException("Could not open Hibernate Session", ex);
	}
}
 
Example 6
Project: lams   File: OpenSessionInViewInterceptor.java   Source Code and License Vote up 5 votes
/**
 * Open a Session for the SessionFactory that this interceptor uses.
 * <p>The default implementation delegates to the {@link SessionFactory#openSession}
 * method and sets the {@link Session}'s flush mode to "MANUAL".
 * @return the Session to use
 * @throws DataAccessResourceFailureException if the Session could not be created
 * @see org.hibernate.FlushMode#MANUAL
 */
protected Session openSession() throws DataAccessResourceFailureException {
	try {
		Session session = getSessionFactory().openSession();
		session.setFlushMode(FlushMode.MANUAL);
		return session;
	}
	catch (HibernateException ex) {
		throw new DataAccessResourceFailureException("Could not open Hibernate Session", ex);
	}
}
 
Example 7
Project: lams   File: OpenSessionInViewFilter.java   Source Code and License Vote up 5 votes
/**
 * Open a Session for the SessionFactory that this filter uses.
 * <p>The default implementation delegates to the {@link SessionFactory#openSession}
 * method and sets the {@link Session}'s flush mode to "MANUAL".
 * @param sessionFactory the SessionFactory that this filter uses
 * @return the Session to use
 * @throws DataAccessResourceFailureException if the Session could not be created
 * @see org.hibernate.FlushMode#MANUAL
 */
protected Session openSession(SessionFactory sessionFactory) throws DataAccessResourceFailureException {
	try {
		Session session = sessionFactory.openSession();
		session.setFlushMode(FlushMode.MANUAL);
		return session;
	}
	catch (HibernateException ex) {
		throw new DataAccessResourceFailureException("Could not open Hibernate Session", ex);
	}
}
 
Example 8
Project: lams   File: SpringSessionSynchronization.java   Source Code and License Vote up 5 votes
@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());
	}
	// Eagerly disconnect the Session here, to make release mode "on_close" work nicely.
	session.disconnect();
}
 
Example 9
Project: lams   File: SpringJtaSessionContext.java   Source Code and License Vote up 5 votes
@Override
protected Session buildOrObtainSession() {
	Session session = super.buildOrObtainSession();
	if (TransactionSynchronizationManager.isCurrentTransactionReadOnly()) {
		session.setFlushMode(FlushMode.MANUAL);
	}
	return session;
}
 
Example 10
Project: lams   File: OpenSessionInterceptor.java   Source Code and License Vote up 5 votes
/**
 * Open a Session for the SessionFactory that this interceptor uses.
 * <p>The default implementation delegates to the {@link SessionFactory#openSession}
 * method and sets the {@link Session}'s flush mode to "MANUAL".
 * @return the Session to use
 * @throws DataAccessResourceFailureException if the Session could not be created
 * @see org.hibernate.FlushMode#MANUAL
 */
protected Session openSession() throws DataAccessResourceFailureException {
	try {
		Session session = getSessionFactory().openSession();
		session.setFlushMode(FlushMode.MANUAL);
		return session;
	}
	catch (HibernateException ex) {
		throw new DataAccessResourceFailureException("Could not open Hibernate Session", ex);
	}
}
 
Example 11
Project: lams   File: SessionFactoryUtils.java   Source Code and License Vote up 5 votes
/**
 * Close the given Session or register it for deferred close.
 * @param session the Hibernate Session to close
 * @param sessionFactory Hibernate SessionFactory that the Session was created with
 * (may be {@code null})
 * @see #initDeferredClose
 * @see #processDeferredClose
 */
static void closeSessionOrRegisterDeferredClose(Session session, SessionFactory sessionFactory) {
	Map<SessionFactory, Set<Session>> holderMap = deferredCloseHolder.get();
	if (holderMap != null && sessionFactory != null && holderMap.containsKey(sessionFactory)) {
		logger.debug("Registering Hibernate Session for deferred close");
		// Switch Session to FlushMode.MANUAL for remaining lifetime.
		session.setFlushMode(FlushMode.MANUAL);
		Set<Session> sessions = holderMap.get(sessionFactory);
		sessions.add(session);
	}
	else {
		closeSession(session);
	}
}
 
Example 12
Project: lams   File: TransactionAwareSessionContext.java   Source Code and License Vote up 5 votes
/**
    * Binds the configured session to Spring's transaction manager strategy if there's no session.
    *
    * @return Returns the configured session, or the one managed by Spring. Never returns null.
    */
   @Override
   public Session currentSession() {
try {
    Session s = defaultSessionContext.currentSession();
    return s;
} catch (HibernateException cause) {

    // There's no session bound to the current thread. Let's open one if
    // needed.
    if (ManagedSessionContext.hasBind(sessionFactory)) {
	return localSessionContext.currentSession();
    }

    Session session;
    session = sessionFactory.openSession();
    TransactionAwareSessionContext.logger.warn("No Session bound to current Thread. Opened new Session ["
	    + session + "]. Transaction: " + session.getTransaction());

    if (registerSynchronization(session)) {
	// Normalizes Session flush mode, defaulting it to AUTO. Required for
	// synchronization.
	FlushMode flushMode = session.getFlushMode();

	if (FlushMode.isManualFlushMode(flushMode)
		&& !TransactionSynchronizationManager.isCurrentTransactionReadOnly()) {
	    session.setFlushMode(FlushMode.AUTO);
	}
    }
    ManagedSessionContext.bind(session);

    return session;
}
   }
 
Example 13
Project: gitplex-mit   File: TransactionInterceptor.java   Source Code and License Vote up 5 votes
public Object invoke(MethodInvocation mi) throws Throwable {
	if (persistManager.getSessionFactory() != null) {
		unitOfWork.begin();
		try {
			Session session = unitOfWork.getSession();
			if (session.getTransaction().getStatus() == TransactionStatus.ACTIVE) {
				return mi.proceed();
			} else {
				Transaction tx = session.beginTransaction();
				FlushMode previousMode = session.getFlushMode();
				session.setFlushMode(FlushMode.COMMIT);
				try {
					Object result = mi.proceed();
					tx.commit();
					return result;
				} catch (Throwable t) {
					try {
						tx.rollback();
					} catch (Throwable t2) {
					}
					throw t;
				} finally {
					session.setFlushMode(previousMode);
				}
			}
			
		} finally {
			unitOfWork.end();
		}
	} else {
		return mi.proceed();
	}
}
 
Example 14
Project: lams   File: HibernateTransactionManager.java   Source Code and License Vote up 4 votes
@Override
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 = ((SessionImplementor) 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 [" + session + "] after transaction");
		}
		SessionFactoryUtils.closeSession(session);
	}
	else {
		if (logger.isDebugEnabled()) {
			logger.debug("Not closing pre-bound Hibernate Session [" + session + "] after transaction");
		}
		if (txObject.getSessionHolder().getPreviousFlushMode() != null) {
			session.setFlushMode(txObject.getSessionHolder().getPreviousFlushMode());
		}
		if (!this.hibernateManagedSession) {
			session.disconnect();
		}
	}
	txObject.getSessionHolder().clear();
}
 
Example 15
Project: lams   File: HibernateInterceptor.java   Source Code and License Vote up 4 votes
@Override
public Object invoke(MethodInvocation methodInvocation) throws Throwable {
	Session session = getSession();
	SessionHolder sessionHolder =
			(SessionHolder) TransactionSynchronizationManager.getResource(getSessionFactory());

	boolean existingTransaction = (sessionHolder != null && sessionHolder.containsSession(session));
	if (existingTransaction) {
		logger.debug("Found thread-bound Session for HibernateInterceptor");
	}
	else {
		if (sessionHolder != null) {
			sessionHolder.addSession(session);
		}
		else {
			TransactionSynchronizationManager.bindResource(getSessionFactory(), new SessionHolder(session));
		}
	}

	FlushMode previousFlushMode = null;
	try {
		previousFlushMode = applyFlushMode(session, existingTransaction);
		enableFilters(session);
		Object retVal = methodInvocation.proceed();
		flushIfNecessary(session, existingTransaction);
		return retVal;
	}
	catch (HibernateException ex) {
		if (this.exceptionConversionEnabled) {
			throw convertHibernateAccessException(ex);
		}
		else {
			throw ex;
		}
	}
	finally {
		if (existingTransaction) {
			logger.debug("Not closing pre-bound Hibernate Session after HibernateInterceptor");
			disableFilters(session);
			if (previousFlushMode != null) {
				session.setFlushMode(previousFlushMode);
			}
		}
		else {
			SessionFactoryUtils.closeSessionOrRegisterDeferredClose(session, getSessionFactory());
			if (sessionHolder == null || sessionHolder.doesNotHoldNonDefaultSession()) {
				TransactionSynchronizationManager.unbindResource(getSessionFactory());
			}
		}
	}
}
 
Example 16
Project: lams   File: SessionFactoryUtils.java   Source Code and License Vote up 4 votes
/**
 * Retrieve a Session from the given SessionHolder, potentially from a
 * JTA transaction synchronization.
 * @param sessionHolder the SessionHolder to check
 * @param sessionFactory the SessionFactory to get the JTA TransactionManager from
 * @param jdbcExceptionTranslator SQLExcepionTranslator to use for flushing the
 * Session on transaction synchronization (may be {@code null})
 * @return the associated Session, if any
 * @throws DataAccessResourceFailureException if the Session couldn't be created
 */
private static Session getJtaSynchronizedSession(
		SessionHolder sessionHolder, SessionFactory sessionFactory,
		SQLExceptionTranslator jdbcExceptionTranslator) throws DataAccessResourceFailureException {

	// JTA synchronization is only possible with a javax.transaction.TransactionManager.
	// We'll check the Hibernate SessionFactory: If a TransactionManagerLookup is specified
	// in Hibernate configuration, it will contain a TransactionManager reference.
	TransactionManager jtaTm = getJtaTransactionManager(sessionFactory, sessionHolder.getAnySession());
	if (jtaTm != null) {
		// Check whether JTA transaction management is active ->
		// fetch pre-bound Session for the current JTA transaction, if any.
		// (just necessary for JTA transaction suspension, with an individual
		// Hibernate Session per currently active/suspended transaction)
		try {
			// Look for transaction-specific Session.
			Transaction jtaTx = jtaTm.getTransaction();
			if (jtaTx != null) {
				int jtaStatus = jtaTx.getStatus();
				if (jtaStatus == Status.STATUS_ACTIVE || jtaStatus == Status.STATUS_MARKED_ROLLBACK) {
					Session session = sessionHolder.getValidatedSession(jtaTx);
					if (session == null && !sessionHolder.isSynchronizedWithTransaction()) {
						// No transaction-specific Session found: If not already marked as
						// synchronized with transaction, register the default thread-bound
						// Session as JTA-transactional. If there is no default Session,
						// we're a new inner JTA transaction with an outer one being suspended:
						// In that case, we'll return null to trigger opening of a new Session.
						session = sessionHolder.getValidatedSession();
						if (session != null) {
							logger.debug("Registering JTA transaction synchronization for existing Hibernate Session");
							sessionHolder.addSession(jtaTx, session);
							jtaTx.registerSynchronization(
									new SpringJtaSynchronizationAdapter(
											new SpringSessionSynchronization(sessionHolder, sessionFactory, jdbcExceptionTranslator, false),
											jtaTm));
							sessionHolder.setSynchronizedWithTransaction(true);
							// Switch to FlushMode.AUTO, as we have to assume a thread-bound Session
							// with FlushMode.NEVER, which needs to allow flushing within the transaction.
							FlushMode flushMode = session.getFlushMode();
							if (flushMode.lessThan(FlushMode.COMMIT)) {
								session.setFlushMode(FlushMode.AUTO);
								sessionHolder.setPreviousFlushMode(flushMode);
							}
						}
					}
					return session;
				}
			}
			// No transaction active -> simply return default thread-bound Session, if any
			// (possibly from OpenSessionInViewFilter/Interceptor).
			return sessionHolder.getValidatedSession();
		}
		catch (Throwable ex) {
			throw new DataAccessResourceFailureException("Could not check JTA transaction", ex);
		}
	}
	else {
		// No JTA TransactionManager -> simply return default thread-bound Session, if any
		// (possibly from OpenSessionInViewFilter/Interceptor).
		return sessionHolder.getValidatedSession();
	}
}
 
Example 17
Project: lams   File: HibernateTransactionManager.java   Source Code and License Vote up 4 votes
@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 18
Project: lams   File: OpenSessionInViewFilter.java   Source Code and License Vote up 3 votes
/**
 * Get a Session for the SessionFactory that this filter uses.
 * Note that this just applies in single session mode!
 * <p>The default implementation delegates to the
 * {@code SessionFactoryUtils.getSession} method and
 * sets the {@code Session}'s flush mode to "MANUAL".
 * <p>Can be overridden in subclasses for creating a Session with a
 * custom entity interceptor or JDBC exception translator.
 * @param sessionFactory the SessionFactory that this filter uses
 * @return the Session to use
 * @throws DataAccessResourceFailureException if the Session could not be created
 * @see org.springframework.orm.hibernate3.SessionFactoryUtils#getSession(SessionFactory, boolean)
 * @see org.hibernate.FlushMode#MANUAL
 */
protected Session getSession(SessionFactory sessionFactory) throws DataAccessResourceFailureException {
	Session session = SessionFactoryUtils.getSession(sessionFactory, true);
	FlushMode flushMode = getFlushMode();
	if (flushMode != null) {
		session.setFlushMode(flushMode);
	}
	return session;
}
 
Example 19
Project: lams   File: CustomizedOpenSessionInViewFilter.java   Source Code and License Vote up 3 votes
/**
    * Get a Session for the SessionFactory that this filter uses.
    * Note that this just applies in single session mode!
    * <p>
    * The default implementation delegates to SessionFactoryUtils'
    * getSession method and sets the Session's flushMode to NEVER.
    * <p>
    * Can be overridden in subclasses for creating a Session with a custom
    * entity interceptor or JDBC exception translator.
    * 
    * @param sessionFactory
    *            the SessionFactory that this filter uses
    * @return the Session to use
    * @throws DataAccessResourceFailureException
    *             if the Session could not be created
    * @see org.springframework.orm.hibernate4.SessionFactoryUtils#getSession(SessionFactory, boolean)
    * @see org.hibernate.FlushMode#NEVER
    */
   @Override
   protected Session openSession(SessionFactory sessionFactory) throws DataAccessResourceFailureException {
try {
    Session session = sessionFactory.openSession();
    session.setFlushMode(FlushMode.AUTO);
    return session;
} catch (HibernateException ex) {
    throw new DataAccessResourceFailureException("Could not open Hibernate Session", ex);
}
   }