List of usage examples for org.hibernate Session setFlushMode
@Deprecated
void setFlushMode(FlushMode flushMode);
From source file:org.springframework.orm.hibernate3.HibernateInterceptor.java
License:Apache License
@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 {//ww w . j a v a2 s .c o m 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()); } } } }
From source file:org.springframework.orm.hibernate3.HibernateTemplate.java
License:Apache License
/** * Execute the action specified by the given action object within a Session. * @param action callback object that specifies the Hibernate action * @param enforceNewSession whether to enforce a new Session for this template * even if there is a pre-bound transactional Session * @param enforceNativeSession whether to enforce exposure of the native * Hibernate Session to callback code/* w w w.j av a 2 s . co m*/ * @return a result object returned by the action, or {@code null} * @throws org.springframework.dao.DataAccessException in case of Hibernate errors */ protected <T> T doExecute(HibernateCallback<T> action, boolean enforceNewSession, boolean enforceNativeSession) throws DataAccessException { Assert.notNull(action, "Callback object must not be null"); Session session = (enforceNewSession ? SessionFactoryUtils.getNewSession(getSessionFactory(), getEntityInterceptor()) : getSession()); boolean existingTransaction = (!enforceNewSession && (!isAllowCreate() || SessionFactoryUtils.isSessionTransactional(session, getSessionFactory()))); if (existingTransaction) { logger.debug("Found thread-bound Session for HibernateTemplate"); } FlushMode previousFlushMode = null; try { previousFlushMode = applyFlushMode(session, existingTransaction); enableFilters(session); Session sessionToExpose = (enforceNativeSession || isExposeNativeSession() ? session : createSessionProxy(session)); T result = action.doInHibernate(sessionToExpose); flushIfNecessary(session, existingTransaction); return result; } catch (HibernateException ex) { throw convertHibernateAccessException(ex); } catch (SQLException ex) { throw convertJdbcAccessException(ex); } catch (RuntimeException ex) { // Callback code threw application exception... throw ex; } finally { if (existingTransaction) { logger.debug("Not closing pre-bound Hibernate Session after HibernateTemplate"); disableFilters(session); if (previousFlushMode != null) { session.setFlushMode(previousFlushMode); } } else { // Never use deferred close for an explicitly new Session. if (isAlwaysUseNewSession()) { SessionFactoryUtils.closeSession(session); } else { SessionFactoryUtils.closeSessionOrRegisterDeferredClose(session, getSessionFactory()); } } } }
From source file:org.springframework.orm.hibernate3.HibernateTransactionManager.java
License:Apache License
@Override @SuppressWarnings("deprecation") protected void doBegin(Object transaction, TransactionDefinition definition) { HibernateTransactionObject txObject = (HibernateTransactionObject) transaction; if (txObject.hasConnectionHolder() && !txObject.getConnectionHolder().isSynchronizedWithTransaction()) { throw new IllegalTransactionStateException( "Pre-bound JDBC Connection found! HibernateTransactionManager does not support " + "running within DataSourceTransactionManager if told to manage the DataSource itself. " + "It is recommended to use a single HibernateTransactionManager for all transactions " + "on a single DataSource, no matter whether Hibernate or JDBC access."); }//from ww w.j a va 2 s . c o m Session session = null; try { if (txObject.getSessionHolder() == null || txObject.getSessionHolder().isSynchronizedWithTransaction()) { Interceptor entityInterceptor = getEntityInterceptor(); Session newSession = (entityInterceptor != null ? getSessionFactory().openSession(entityInterceptor) : getSessionFactory().openSession()); if (logger.isDebugEnabled()) { logger.debug("Opened new Session [" + SessionFactoryUtils.toString(newSession) + "] for Hibernate transaction"); } txObject.setSession(newSession); } session = txObject.getSessionHolder().getSession(); if (this.prepareConnection && isSameConnectionForEntireSession(session)) { // We're allowed to change the transaction settings of the JDBC Connection. if (logger.isDebugEnabled()) { logger.debug("Preparing JDBC Connection of Hibernate Session [" + SessionFactoryUtils.toString(session) + "]"); } Connection con = session.connection(); Integer previousIsolationLevel = DataSourceUtils.prepareConnectionForTransaction(con, definition); txObject.setPreviousIsolationLevel(previousIsolationLevel); } else { // Not allowed to change the transaction settings of the JDBC Connection. if (definition.getIsolationLevel() != TransactionDefinition.ISOLATION_DEFAULT) { // We should set a specific isolation level but are not allowed to... throw new InvalidIsolationLevelException( "HibernateTransactionManager is not allowed to support custom isolation levels: " + "make sure that its 'prepareConnection' flag is on (the default) and that the " + "Hibernate connection release mode is set to 'on_close' (SpringTransactionFactory's default). " + "Make sure that your LocalSessionFactoryBean actually uses SpringTransactionFactory: Your " + "Hibernate properties should *not* include a 'hibernate.transaction.factory_class' property!"); } if (logger.isDebugEnabled()) { logger.debug("Not preparing JDBC Connection of Hibernate Session [" + SessionFactoryUtils.toString(session) + "]"); } } if (definition.isReadOnly() && txObject.isNewSession()) { // Just set to MANUAL in case of a new Session for this transaction. session.setFlushMode(FlushMode.MANUAL); } if (!definition.isReadOnly() && !txObject.isNewSession()) { // We need AUTO or COMMIT for a non-read-only transaction. FlushMode flushMode = session.getFlushMode(); if (flushMode.lessThan(FlushMode.COMMIT)) { session.setFlushMode(FlushMode.AUTO); txObject.getSessionHolder().setPreviousFlushMode(flushMode); } } Transaction hibTx; // Register transaction timeout. int timeout = determineTimeout(definition); if (timeout != TransactionDefinition.TIMEOUT_DEFAULT) { // Use Hibernate's own transaction timeout mechanism on Hibernate 3.1+ // Applies to all statements, also to inserts, updates and deletes! hibTx = session.getTransaction(); hibTx.setTimeout(timeout); hibTx.begin(); } else { // Open a plain Hibernate transaction without specified timeout. hibTx = session.beginTransaction(); } // Add the Hibernate transaction to the session holder. txObject.getSessionHolder().setTransaction(hibTx); // Register the Hibernate Session's JDBC Connection for the DataSource, if set. if (getDataSource() != null) { Connection con = session.connection(); ConnectionHolder conHolder = new ConnectionHolder(con); if (timeout != TransactionDefinition.TIMEOUT_DEFAULT) { conHolder.setTimeoutInSeconds(timeout); } if (logger.isDebugEnabled()) { logger.debug("Exposing Hibernate transaction as JDBC transaction [" + con + "]"); } TransactionSynchronizationManager.bindResource(getDataSource(), conHolder); txObject.setConnectionHolder(conHolder); } // Bind the session holder to the thread. if (txObject.isNewSessionHolder()) { TransactionSynchronizationManager.bindResource(getSessionFactory(), txObject.getSessionHolder()); } txObject.getSessionHolder().setSynchronizedWithTransaction(true); } catch (Throwable ex) { if (txObject.isNewSession()) { try { if (session.getTransaction().isActive()) { session.getTransaction().rollback(); } } catch (Throwable ex2) { logger.debug("Could not rollback Session after failed transaction begin", ex); } finally { SessionFactoryUtils.closeSession(session); txObject.setSessionHolder(null); } } throw new CannotCreateTransactionException("Could not open Hibernate Session for transaction", ex); } }
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()); }/*from w w w . ja v a2 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.SessionFactoryUtils.java
License:Apache License
/** * Get a Hibernate Session for the given SessionFactory. Is aware of and will * return any existing corresponding Session bound to the current thread, for * example when using {@link HibernateTransactionManager}. Will create a new * Session otherwise, if "allowCreate" is {@code true}. * <p>Same as {@link #getSession}, but throwing the original HibernateException. * @param sessionFactory Hibernate SessionFactory to create the session with * @param entityInterceptor Hibernate entity interceptor, or {@code null} if none * @param jdbcExceptionTranslator SQLExcepionTranslator to use for flushing the * Session on transaction synchronization (may be {@code null}) * @param allowCreate whether a non-transactional Session should be created * when no transactional Session can be found for the current thread * @return the Hibernate Session/*from w ww.j av a 2 s .co m*/ * @throws HibernateException if the Session couldn't be created * @throws IllegalStateException if no thread-bound Session found and * "allowCreate" is {@code false} */ private static Session doGetSession(SessionFactory sessionFactory, Interceptor entityInterceptor, SQLExceptionTranslator jdbcExceptionTranslator, boolean allowCreate) throws HibernateException, IllegalStateException { Assert.notNull(sessionFactory, "No SessionFactory specified"); Object resource = TransactionSynchronizationManager.getResource(sessionFactory); if (resource instanceof Session) { return (Session) resource; } SessionHolder sessionHolder = (SessionHolder) resource; if (sessionHolder != null && !sessionHolder.isEmpty()) { // pre-bound Hibernate Session Session session = null; if (TransactionSynchronizationManager.isSynchronizationActive() && sessionHolder.doesNotHoldNonDefaultSession()) { // Spring transaction management is active -> // register pre-bound Session with it for transactional flushing. session = sessionHolder.getValidatedSession(); if (session != null && !sessionHolder.isSynchronizedWithTransaction()) { logger.debug("Registering Spring transaction synchronization for existing Hibernate Session"); TransactionSynchronizationManager.registerSynchronization(new SpringSessionSynchronization( sessionHolder, sessionFactory, jdbcExceptionTranslator, false)); 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.lessThan(FlushMode.COMMIT) && !TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { session.setFlushMode(FlushMode.AUTO); sessionHolder.setPreviousFlushMode(flushMode); } } } else { // No Spring transaction management active -> try JTA transaction synchronization. session = getJtaSynchronizedSession(sessionHolder, sessionFactory, jdbcExceptionTranslator); } if (session != null) { return session; } } logger.debug("Opening Hibernate Session"); Session session = (entityInterceptor != null ? sessionFactory.openSession(entityInterceptor) : sessionFactory.openSession()); // Use same Session for further Hibernate actions within the transaction. // Thread object will get removed by synchronization at transaction completion. if (TransactionSynchronizationManager.isSynchronizationActive()) { // We're within a Spring-managed transaction, possibly from JtaTransactionManager. logger.debug("Registering Spring transaction synchronization for new Hibernate Session"); SessionHolder holderToUse = sessionHolder; if (holderToUse == null) { holderToUse = new SessionHolder(session); } else { holderToUse.addSession(session); } if (TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { session.setFlushMode(FlushMode.MANUAL); } TransactionSynchronizationManager.registerSynchronization( new SpringSessionSynchronization(holderToUse, sessionFactory, jdbcExceptionTranslator, true)); holderToUse.setSynchronizedWithTransaction(true); if (holderToUse != sessionHolder) { TransactionSynchronizationManager.bindResource(sessionFactory, holderToUse); } } else { // No Spring transaction management active -> try JTA transaction synchronization. registerJtaSynchronization(session, sessionFactory, jdbcExceptionTranslator, sessionHolder); } // Check whether we are allowed to return the Session. if (!allowCreate && !isSessionTransactional(session, sessionFactory)) { closeSession(session); throw new IllegalStateException("No Hibernate Session bound to thread, " + "and configuration does not allow creation of non-transactional one here"); } return session; }
From source file:org.springframework.orm.hibernate3.SessionFactoryUtils.java
License:Apache License
/** * Retrieve a Session from the given SessionHolder, potentially from a * JTA transaction synchronization./*w w w . ja v a 2 s.c om*/ * @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(); } }
From source file:org.springframework.orm.hibernate3.SessionFactoryUtils.java
License:Apache License
/** * 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})/*from ww w. ja va 2 s .c o m*/ * @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); } }
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 . ja 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.StatelessHibernateTemplate.java
License:Apache License
/** * Execute the action specified by the given action object within a Session. * @param action callback object that specifies the Hibernate action * @param exposeNativeSession whether to expose the native Hibernate Session * to callback code/*from w w w . jav a2 s . com*/ * @return a result object returned by the action, or <code>null</code> * @throws org.springframework.dao.DataAccessException in case of Hibernate errors */ public Object execute(HibernateCallback action, boolean exposeNativeSession) throws DataAccessException { Assert.notNull(action, "Callback object must not be null"); Session session = getSession(); boolean existingTransaction = (!isAlwaysUseNewSession() && (!isAllowCreate() || SessionFactoryUtils.isSessionTransactional(session, getSessionFactory()))); if (existingTransaction) { logger.debug("Found thread-bound Session for HibernateTemplate"); } FlushMode previousFlushMode = null; try { previousFlushMode = applyFlushMode(session, existingTransaction); enableFilters(session); Session sessionToExpose = (exposeNativeSession ? session : createSessionProxy(session)); Object result = action.doInHibernate(sessionToExpose); flushIfNecessary(session, existingTransaction); return result; } catch (HibernateException ex) { throw convertHibernateAccessException(ex); } catch (SQLException ex) { throw convertJdbcAccessException(ex); } catch (RuntimeException ex) { // Callback code threw application exception... throw ex; } finally { if (existingTransaction) { logger.debug("Not closing pre-bound Hibernate Session after HibernateTemplate"); disableFilters(session); if (previousFlushMode != null) { session.setFlushMode(previousFlushMode); } } else { // Never use deferred close for an explicitly new Session. if (isAlwaysUseNewSession()) { SessionFactoryUtils.closeSession(session); } else { SessionFactoryUtils.closeSessionOrRegisterDeferredClose(session, getSessionFactory()); } } } }
From source file:org.springframework.orm.hibernate3.support.OpenSessionInterceptor.java
License:Apache License
/** * 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//from ww w .j a v a 2 s . co m * @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); } }