org.hibernate.Session.setFlushMode() - java examples

Here are the examples of the java api org.hibernate.Session.setFlushMode() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

61 Examples 7

19 View Complete Implementation : HibernateJpaDialect.java
Copyright Apache License 2.0
Author : langtianya
protected FlushMode prepareFlushMode(Session session, boolean readOnly) throws PersistenceException {
    FlushMode flushMode = session.getFlushMode();
    if (readOnly) {
        // We should suppress flushing for a read-only transaction.
        if (!flushMode.equals(FlushMode.MANUAL)) {
            session.setFlushMode(FlushMode.MANUAL);
            return flushMode;
        }
    } else {
        // We need AUTO or COMMIT for a non-read-only transaction.
        if (flushMode.lessThan(FlushMode.COMMIT)) {
            session.setFlushMode(FlushMode.AUTO);
            return flushMode;
        }
    }
    // No FlushMode change needed...
    return null;
}

19 View Complete Implementation : OpenSessionInterceptor.java
Copyright Apache License 2.0
Author : langtianya
/**
 * 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 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);
    }
}

19 View Complete Implementation : HibernateAccessor.java
Copyright Apache License 2.0
Author : langtianya
/**
 * Apply the flush mode that's been specified for this accessor
 * to the given Session.
 * @param session the current Hibernate Session
 * @param existingTransaction if executing within an existing transaction
 * @return the previous flush mode to restore after the operation,
 * or {@code null} if none
 * @see #setFlushMode
 * @see org.hibernate.Session#setFlushMode
 */
protected FlushMode applyFlushMode(Session session, boolean existingTransaction) {
    if (getFlushMode() == FLUSH_NEVER) {
        if (existingTransaction) {
            FlushMode previousFlushMode = session.getFlushMode();
            if (!previousFlushMode.lessThan(FlushMode.COMMIT)) {
                session.setFlushMode(FlushMode.MANUAL);
                return previousFlushMode;
            }
        } else {
            session.setFlushMode(FlushMode.MANUAL);
        }
    } else if (getFlushMode() == FLUSH_EAGER) {
        if (existingTransaction) {
            FlushMode previousFlushMode = session.getFlushMode();
            if (!previousFlushMode.equals(FlushMode.AUTO)) {
                session.setFlushMode(FlushMode.AUTO);
                return previousFlushMode;
            }
        } else {
        // rely on default FlushMode.AUTO
        }
    } else if (getFlushMode() == FLUSH_COMMIT) {
        if (existingTransaction) {
            FlushMode previousFlushMode = session.getFlushMode();
            if (previousFlushMode.equals(FlushMode.AUTO) || previousFlushMode.equals(FlushMode.ALWAYS)) {
                session.setFlushMode(FlushMode.COMMIT);
                return previousFlushMode;
            }
        } else {
            session.setFlushMode(FlushMode.COMMIT);
        }
    } else if (getFlushMode() == FLUSH_ALWAYS) {
        if (existingTransaction) {
            FlushMode previousFlushMode = session.getFlushMode();
            if (!previousFlushMode.equals(FlushMode.ALWAYS)) {
                session.setFlushMode(FlushMode.ALWAYS);
                return previousFlushMode;
            }
        } else {
            session.setFlushMode(FlushMode.ALWAYS);
        }
    }
    return null;
}

19 View Complete Implementation : OpenSessionInViewInterceptor.java
Copyright MIT License
Author : codeEngraver
/**
 * 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 FlushMode#MANUAL
 */
@SuppressWarnings("deprecation")
protected Session openSession() throws DataAccessResourceFailureException {
    try {
        Session session = obtainSessionFactory().openSession();
        session.setFlushMode(FlushMode.MANUAL);
        return session;
    } catch (HibernateException ex) {
        throw new DataAccessResourceFailureException("Could not open Hibernate Session", ex);
    }
}

19 View Complete Implementation : EntityManagerUtil.java
Copyright Apache License 2.0
Author : softwaremill
/**
 * Changes the given enreplacedy manager to be read only. No changes will be flushed automatically. Also all enreplacedies
 * will be marked as read only by Hibernate.
 * @param em The enreplacedy manager to make read only.
 */
public static void makeEnreplacedyManagerReadOnly(EnreplacedyManager em) {
    Session readOnlySession = (Session) em.getDelegate();
    readOnlySession.setDefaultReadOnly(true);
    readOnlySession.setFlushMode(FlushMode.MANUAL);
}

19 View Complete Implementation : OpenSessionInViewFilter.java
Copyright Apache License 2.0
Author : langtianya
/**
 * 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 subclreplacedes for creating a Session with a
 * custom enreplacedy 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;
}

19 View Complete Implementation : SpringJtaSessionContext.java
Copyright Apache License 2.0
Author : langtianya
@Override
protected Session buildOrObtainSession() {
    Session session = super.buildOrObtainSession();
    if (TransactionSynchronizationManager.isCurrentTransactionReadOnly()) {
        session.setFlushMode(FlushMode.MANUAL);
    }
    return session;
}

19 View Complete Implementation : HibernateTemplate.java
Copyright MIT License
Author : codeEngraver
/**
 * Execute the action specified by the given action object within a Session.
 * @param action callback object that specifies the Hibernate action
 * @param enforceNativeSession whether to enforce exposure of the native
 * Hibernate Session to callback code
 * @return a result object returned by the action, or {@code null}
 * @throws DataAccessException in case of Hibernate errors
 */
@SuppressWarnings("deprecation")
@Nullable
protected <T> T doExecute(HibernateCallback<T> action, boolean enforceNativeSession) throws DataAccessException {
    replacedert.notNull(action, "Callback object must not be null");
    Session session = null;
    boolean isNew = false;
    try {
        session = obtainSessionFactory().getCurrentSession();
    } catch (HibernateException ex) {
        logger.debug("Could not retrieve pre-bound Hibernate session", ex);
    }
    if (session == null) {
        session = obtainSessionFactory().openSession();
        session.setFlushMode(FlushMode.MANUAL);
        isNew = true;
    }
    try {
        enableFilters(session);
        Session sessionToExpose = (enforceNativeSession || isExposeNativeSession() ? session : createSessionProxy(session));
        return action.doInHibernate(sessionToExpose);
    } catch (HibernateException ex) {
        throw SessionFactoryUtils.convertHibernateAccessException(ex);
    } catch (PersistenceException ex) {
        if (ex.getCause() instanceof HibernateException) {
            throw SessionFactoryUtils.convertHibernateAccessException((HibernateException) ex.getCause());
        }
        throw ex;
    } catch (RuntimeException ex) {
        // Callback code threw application exception...
        throw ex;
    } finally {
        if (isNew) {
            SessionFactoryUtils.closeSession(session);
        } else {
            disableFilters(session);
        }
    }
}

19 View Complete Implementation : Transaction.java
Copyright GNU Lesser General Public License v3.0
Author : robeio
/**
 * Opens a new session, sets flush mode and bind this session to {@link ManagedSessionContext}
 */
private void configureNewSession() {
    session = SESSION_FACTORY.openSession();
    session.setFlushMode(flushMode);
    ManagedSessionContext.bind(session);
}

19 View Complete Implementation : HibernateTransactionManager.java
Copyright Apache License 2.0
Author : langtianya
@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);
            }
        }
    }
}

19 View Complete Implementation : OpenSessionInterceptor.java
Copyright Apache License 2.0
Author : langtianya
/**
 * 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);
    }
}

19 View Complete Implementation : SessionFactoryUtils.java
Copyright Apache License 2.0
Author : langtianya
/**
 * 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 replacedociated 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 replacedume 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();
    }
}

19 View Complete Implementation : SessionFactoryUtils.java
Copyright Apache License 2.0
Author : langtianya
/**
 * 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);
    }
}

19 View Complete Implementation : ProxyTest.java
Copyright GNU Lesser General Public License v2.1
Author : cacheonix
public void testFullyLoadedPCSerialization() {
    Session s = openSession();
    Transaction t = s.beginTransaction();
    Long lastContainerId = null;
    int containerCount = 10;
    int nestedDataPointCount = 5;
    for (int c_indx = 0; c_indx < containerCount; c_indx++) {
        Owner owner = new Owner("Owner #" + c_indx);
        Container container = new Container("Container #" + c_indx);
        container.setOwner(owner);
        for (int dp_indx = 0; dp_indx < nestedDataPointCount; dp_indx++) {
            DataPoint dp = new DataPoint();
            dp.setDescription("data-point [" + c_indx + ", " + dp_indx + "]");
            // more HSQLDB fun...
            // dp.setX( new BigDecimal( c_indx ) );
            dp.setX(new BigDecimal(c_indx + dp_indx));
            dp.setY(new BigDecimal(dp_indx));
            container.getDataPoints().add(dp);
        }
        s.save(container);
        lastContainerId = container.getId();
    }
    t.commit();
    s.close();
    s = openSession();
    s.setFlushMode(FlushMode.NEVER);
    t = s.beginTransaction();
    // load the last container as a proxy
    Container proxy = (Container) s.load(Container.clreplaced, lastContainerId);
    replacedertFalse(Hibernate.isInitialized(proxy));
    // load the rest back into the PC
    List all = s.createQuery("from Container as c inner join fetch c.owner inner join fetch c.dataPoints where c.id <> :last").setLong("last", lastContainerId.longValue()).list();
    Container container = (Container) all.get(0);
    s.delete(container);
    // force a snapshot retrieval of the proxied container
    SessionImpl sImpl = (SessionImpl) s;
    sImpl.getPersistenceContext().getDatabaseSnapshot(lastContainerId, sImpl.getFactory().getEnreplacedyPersister(Container.clreplaced.getName()));
    replacedertFalse(Hibernate.isInitialized(proxy));
    t.commit();
    // int iterations = 50;
    // long replacedulativeTime = 0;
    // long replacedulativeSize = 0;
    // for ( int i = 0; i < iterations; i++ ) {
    // final long start = System.currentTimeMillis();
    // byte[] bytes = SerializationHelper.serialize( s );
    // SerializationHelper.deserialize( bytes );
    // final long end = System.currentTimeMillis();
    // replacedulativeTime += ( end - start );
    // int size = bytes.length;
    // replacedulativeSize += size;
    // //			System.out.println( "Iteration #" + i + " took " + ( end - start ) + " ms : size = " + size + " bytes" );
    // }
    // System.out.println( "Average time : " + ( replacedulativeTime / iterations ) + " ms" );
    // System.out.println( "Average size : " + ( replacedulativeSize / iterations ) + " bytes" );
    byte[] bytes = SerializationHelper.serialize(s);
    SerializationHelper.deserialize(bytes);
    t = s.beginTransaction();
    int count = s.createQuery("delete DataPoint").executeUpdate();
    replacedertEquals("unexpected DP delete count", (containerCount * nestedDataPointCount), count);
    count = s.createQuery("delete Container").executeUpdate();
    replacedertEquals("unexpected container delete count", containerCount, count);
    count = s.createQuery("delete Owner").executeUpdate();
    replacedertEquals("unexpected owner delete count", containerCount, count);
    t.commit();
    s.close();
}

19 View Complete Implementation : HibernateJpaDialect.java
Copyright MIT License
Author : codeEngraver
@SuppressWarnings("deprecation")
@Nullable
protected FlushMode prepareFlushMode(Session session, boolean readOnly) throws PersistenceException {
    FlushMode flushMode = (FlushMode) ReflectionUtils.invokeMethod(getFlushMode, session);
    replacedert.state(flushMode != null, "No FlushMode from Session");
    if (readOnly) {
        // We should suppress flushing for a read-only transaction.
        if (!flushMode.equals(FlushMode.MANUAL)) {
            session.setFlushMode(FlushMode.MANUAL);
            return flushMode;
        }
    } else {
        // We need AUTO or COMMIT for a non-read-only transaction.
        if (flushMode.lessThan(FlushMode.COMMIT)) {
            session.setFlushMode(FlushMode.AUTO);
            return flushMode;
        }
    }
    // No FlushMode change needed...
    return null;
}

19 View Complete Implementation : HibernateTemplate.java
Copyright Apache License 2.0
Author : langtianya
/**
 * Execute the action specified by the given action object within a Session.
 * @param action callback object that specifies the Hibernate action
 * @param enforceNativeSession whether to enforce exposure of the native
 * Hibernate Session to callback code
 * @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 enforceNativeSession) throws DataAccessException {
    replacedert.notNull(action, "Callback object must not be null");
    Session session = null;
    boolean isNew = false;
    try {
        session = getSessionFactory().getCurrentSession();
    } catch (HibernateException ex) {
        logger.debug("Could not retrieve pre-bound Hibernate session", ex);
    }
    if (session == null) {
        session = getSessionFactory().openSession();
        session.setFlushMode(FlushMode.MANUAL);
        isNew = true;
    }
    try {
        enableFilters(session);
        Session sessionToExpose = (enforceNativeSession || isExposeNativeSession() ? session : createSessionProxy(session));
        return action.doInHibernate(sessionToExpose);
    } catch (HibernateException ex) {
        throw SessionFactoryUtils.convertHibernateAccessException(ex);
    } catch (RuntimeException ex) {
        // Callback code threw application exception...
        throw ex;
    } finally {
        if (isNew) {
            SessionFactoryUtils.closeSession(session);
        } else {
            disableFilters(session);
        }
    }
}

19 View Complete Implementation : JpaPortalEventStore.java
Copyright Apache License 2.0
Author : Jasig
@Override
@RawEventsTransactional
public boolean aggregatePortalEvents(DateTime startTime, DateTime endTime, int maxEvents, Function<PortalEvent, Boolean> handler) {
    final Session session = this.getEnreplacedyManager().unwrap(Session.clreplaced);
    session.setFlushMode(FlushMode.COMMIT);
    final org.hibernate.Query query = session.createQuery(this.selectUnaggregatedQuery);
    query.setParameter(this.startTimeParameter.getName(), startTime);
    query.setParameter(this.endTimeParameter.getName(), endTime);
    if (maxEvents > 0) {
        query.setMaxResults(maxEvents);
    }
    int resultCount = 0;
    for (final ScrollableResults results = query.scroll(ScrollMode.FORWARD_ONLY); results.next(); ) {
        final PersistentPortalEvent persistentPortalEvent = (PersistentPortalEvent) results.get(0);
        final PortalEvent portalEvent;
        try {
            portalEvent = this.toPortalEvent(persistentPortalEvent.getEventData(), persistentPortalEvent.getEventType());
        } catch (RuntimeException e) {
            this.logger.warn("Failed to convert PersistentPortalEvent to PortalEvent: " + persistentPortalEvent, e);
            // Mark the event as error and store the mark to prevent trying to reprocess the
            // broken event data
            persistentPortalEvent.setErrorAggregating(true);
            session.persist(persistentPortalEvent);
            continue;
        }
        try {
            final Boolean eventHandled = handler.apply(portalEvent);
            if (!eventHandled) {
                this.logger.debug("Aggregation stop requested before processing event {}", portalEvent);
                return false;
            }
            // Mark the event as aggregated and store the mark
            persistentPortalEvent.setAggregated(true);
            session.persist(persistentPortalEvent);
            // periodic flush and clear of session to manage memory demands
            if (++resultCount % this.flushPeriod == 0) {
                this.logger.debug("Aggregated {} events, flush and clear {} EnreplacedyManager.", resultCount, BaseRawEventsJpaDao.PERSISTENCE_UNIT_NAME);
                session.flush();
                session.clear();
            }
        } catch (Exception e) {
            this.logger.warn("Failed to aggregate portal event: " + persistentPortalEvent, e);
            // mark the event as erred and move on. This will not be picked up by processing
            // again
            persistentPortalEvent.setErrorAggregating(true);
            session.persist(persistentPortalEvent);
        }
    }
    return true;
}

19 View Complete Implementation : HibernateTemplate.java
Copyright Apache License 2.0
Author : langtianya
/**
 * Execute the action specified by the given action object within a Session.
 * @param action callback object that specifies the Hibernate action
 * @param enforceNativeSession whether to enforce exposure of the native
 * Hibernate Session to callback code
 * @return a result object returned by the action, or {@code null}
 * @throws DataAccessException in case of Hibernate errors
 */
protected <T> T doExecute(HibernateCallback<T> action, boolean enforceNativeSession) throws DataAccessException {
    replacedert.notNull(action, "Callback object must not be null");
    Session session = null;
    boolean isNew = false;
    try {
        session = getSessionFactory().getCurrentSession();
    } catch (HibernateException ex) {
        logger.debug("Could not retrieve pre-bound Hibernate session", ex);
    }
    if (session == null) {
        session = getSessionFactory().openSession();
        session.setFlushMode(FlushMode.MANUAL);
        isNew = true;
    }
    try {
        enableFilters(session);
        Session sessionToExpose = (enforceNativeSession || isExposeNativeSession() ? session : createSessionProxy(session));
        return action.doInHibernate(sessionToExpose);
    } catch (HibernateException ex) {
        throw SessionFactoryUtils.convertHibernateAccessException(ex);
    } catch (RuntimeException ex) {
        // Callback code threw application exception...
        throw ex;
    } finally {
        if (isNew) {
            SessionFactoryUtils.closeSession(session);
        } else {
            disableFilters(session);
        }
    }
}

19 View Complete Implementation : OpenSessionInterceptor.java
Copyright MIT License
Author : codeEngraver
/**
 * Open a Session for the given SessionFactory.
 * <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 to use
 * @return the Session to use
 * @throws DataAccessResourceFailureException if the Session could not be created
 * @since 5.0
 * @see FlushMode#MANUAL
 */
@SuppressWarnings("deprecation")
protected Session openSession(SessionFactory sessionFactory) throws DataAccessResourceFailureException {
    Session session = openSession();
    if (session == null) {
        try {
            session = sessionFactory.openSession();
            session.setFlushMode(FlushMode.MANUAL);
        } catch (HibernateException ex) {
            throw new DataAccessResourceFailureException("Could not open Hibernate Session", ex);
        }
    }
    return session;
}

19 View Complete Implementation : MicronautSessionContext.java
Copyright Apache License 2.0
Author : micronaut-projects
/**
 * Retrieve the Spring-managed Session for the current thread, if any.
 */
@Override
@SuppressWarnings("deprecation")
public Session currentSession() throws HibernateException {
    Object value = TransactionSynchronizationManager.getResource(this.sessionFactory);
    if (value instanceof Session) {
        return (Session) value;
    } else if (value instanceof SessionHolder) {
        // HibernateTransactionManager
        SessionHolder sessionHolder = (SessionHolder) value;
        Session session = sessionHolder.getSession();
        if (!sessionHolder.isSynchronizedWithTransaction() && TransactionSynchronizationManager.isSynchronizationActive()) {
            TransactionSynchronizationManager.registerSynchronization(new SessionSynchronization(sessionHolder, this.sessionFactory, false));
            sessionHolder.setSynchronizedWithTransaction(true);
            // Switch to FlushMode.AUTO, as we have to replacedume a thread-bound Session
            // with FlushMode.MANUAL, which needs to allow flushing within the transaction.
            FlushMode flushMode = session.getHibernateFlushMode();
            if (flushMode.equals(FlushMode.MANUAL) && !TransactionSynchronizationManager.isCurrentTransactionReadOnly()) {
                session.setFlushMode(FlushMode.AUTO);
                sessionHolder.setPreviousFlushMode(flushMode);
            }
        }
        return session;
    } else if (value instanceof EnreplacedyManagerHolder) {
        // JpaTransactionManager
        return ((EnreplacedyManagerHolder) value).getEnreplacedyManager().unwrap(Session.clreplaced);
    }
    if (TransactionSynchronizationManager.isSynchronizationActive()) {
        Session session = this.sessionFactory.openSession();
        if (TransactionSynchronizationManager.isCurrentTransactionReadOnly()) {
            session.setFlushMode(FlushMode.MANUAL);
        }
        SessionHolder sessionHolder = new SessionHolder(session);
        TransactionSynchronizationManager.registerSynchronization(new SessionSynchronization(sessionHolder, this.sessionFactory, true));
        TransactionSynchronizationManager.bindResource(this.sessionFactory, sessionHolder);
        sessionHolder.setSynchronizedWithTransaction(true);
        return session;
    } else {
        throw new HibernateException("Could not obtain transaction-synchronized Session for current thread");
    }
}

19 View Complete Implementation : HibernateTemplate.java
Copyright Apache License 2.0
Author : langtianya
/**
 * 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
 * @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 {
    replacedert.notNull(action, "Callback object must not be null");
    Session session = (enforceNewSession ? SessionFactoryUtils.getNewSession(getSessionFactory(), getEnreplacedyInterceptor()) : 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());
            }
        }
    }
}

19 View Complete Implementation : InSessionExecutions.java
Copyright GNU General Public License v3.0
Author : SeqWare
/**
 * <p>
 * bindSessionToThread.
 * </p>
 *
 * @param mode
 *            a {@link org.hibernate.FlushMode} object.
 */
public static void bindSessionToThread(FlushMode mode) {
    bindSessionToThread();
    session.setFlushMode(mode);
}

19 View Complete Implementation : HibernateSaveProcessor.java
Copyright MIT License
Author : Breeze
/**
 * Persist the changes to the enreplacedies in the SaveWorkState that is preplaceded in.
 * This implements the abstract method in SaveProcessor.
 * After the completion of this method the saveWorkState.toSaveResult method may be called the will
 * return a SaveResult instance.
 * This method both persists the enreplacedies and creates the collection of KeyMappings,
 * which map the temporary keys to their real generated keys.
 * Note that this method sets session.FlushMode = FlushMode.MANUAL, so manual flushes are required.
 * @param saveWorkState
 */
@Override
protected void saveChangesCore(SaveWorkState saveWorkState) {
    _session = _sessionFactory.openSession();
    _session.setFlushMode(FlushMode.MANUAL);
    Transaction tx = _session.getTransaction();
    boolean hasExistingTransaction = tx.isActive();
    if (!hasExistingTransaction)
        tx.begin();
    try {
        // Relate enreplacedies in the saveMap to other enreplacedies, so Hibernate can save the FK values.
        _fixer = new RelationshipFixer(saveWorkState, _session);
        _fixer.fixupRelationships();
        // At this point all enreplacedies are hooked up but are not yet in the session.
        setSaveState(SaveState.AfterFixup);
        // Allow subclreplaced to process enreplacedies before we save them
        saveWorkState.beforeSaveEnreplacedies();
        List<EnreplacedyInfo> saveOrder = _fixer.sortDependencies();
        processSaves(saveOrder);
        // At this point all enreplacedies are hooked up and in the session, and
        // all tempIds have been replaced with real ids.
        // Final chance to process enreplacedies before we save them - all enreplacedies
        // have been added to the session.
        setSaveState(SaveState.BeforeCommit);
        saveWorkState.beforeCommit(_session);
        _session.flush();
        refreshFromSession(saveWorkState);
        if (!hasExistingTransaction)
            tx.commit();
        // so that serialization of saveResult doesn't have issues.
        _fixer.removeRelationships();
    } catch (EnreplacedyErrorsException eee) {
        if (tx.isActive())
            tx.rollback();
        throw eee;
    } catch (PropertyValueException pve) {
        // Hibernate can throw this
        if (tx.isActive())
            tx.rollback();
        EnreplacedyError enreplacedyError = new EnreplacedyError("PropertyValueException", pve.getEnreplacedyName(), null, pve.getPropertyName(), pve.getMessage());
        throw new EnreplacedyErrorsException(enreplacedyError);
    } catch (Exception ex) {
        if (tx.isActive())
            tx.rollback();
        String msg = "Save exception: ";
        if (ex instanceof JDBCException) {
            msg += "SQLException: " + ((JDBCException) ex).getSQLException().getMessage();
        } else {
            // most hibernate exceptions appear here
            msg += ex.getMessage();
        }
        if (_possibleErrors.size() > 0) {
            msg += ". Possible errors: " + _possibleErrors.toString() + " ";
        }
        throw new RuntimeException(msg, ex);
    } finally {
        // if (!hasExistingTransaction) tx.Dispose();
        _session.close();
    }
}

19 View Complete Implementation : ManualFlushTest.java
Copyright Apache License 2.0
Author : vladmihalcea
@Test
public void testFlushSQL() {
    doInJPA(enreplacedyManager -> {
        enreplacedyManager.createNativeQuery("delete from Post").executeUpdate();
    });
    doInJPA(enreplacedyManager -> {
        log.info("testFlushSQL");
        Post post = new Post("Hibernate");
        post.setId(1L);
        enreplacedyManager.persist(post);
        Session session = enreplacedyManager.unwrap(Session.clreplaced);
        session.setFlushMode(FlushMode.MANUAL);
        replacedertTrue(((Number) enreplacedyManager.createQuery("select count(id) from Post").getSingleResult()).intValue() == 0);
        replacedertTrue(((Number) session.createNativeQuery("select count(*) from Post").uniqueResult()).intValue() == 0);
    });
}

19 View Complete Implementation : SpringJtaSessionContext.java
Copyright MIT License
Author : codeEngraver
@Override
@SuppressWarnings("deprecation")
protected Session buildOrObtainSession() {
    Session session = super.buildOrObtainSession();
    if (TransactionSynchronizationManager.isCurrentTransactionReadOnly()) {
        session.setFlushMode(FlushMode.MANUAL);
    }
    return session;
}

19 View Complete Implementation : TreeIntercptor.java
Copyright GNU General Public License v2.0
Author : caipiao
@Override
public boolean onSave(Object enreplacedy, Serializable id, Object[] state, String[] propertyNames, Type[] types) {
    if (enreplacedy instanceof HibernateTree) {
        HibernateTree<?> tree = (HibernateTree<?>) enreplacedy;
        Number parentId = tree.getParentId();
        String beanName = tree.getClreplaced().getName();
        Session session = getSession();
        FlushMode model = session.getFlushMode();
        session.setFlushMode(FlushMode.MANUAL);
        Integer myPosition;
        if (parentId != null) {
            // 如果父节点不为null,则获取节点的右边位置
            String hql = "select bean." + tree.getRgtName() + " from " + beanName + " bean where bean.id=:pid";
            myPosition = ((Number) session.createQuery(hql).setParameter("pid", parentId).uniqueResult()).intValue();
            String hql1 = "update " + beanName + " bean set bean." + tree.getRgtName() + " = bean." + tree.getRgtName() + " + 2 WHERE bean." + tree.getRgtName() + " >= :myPosition";
            String hql2 = "update " + beanName + " bean set bean." + tree.getLftName() + " = bean." + tree.getLftName() + " + 2 WHERE bean." + tree.getLftName() + " >= :myPosition";
            if (!StringUtils.isBlank(tree.getTreeCondition())) {
                hql1 += " and (" + tree.getTreeCondition() + ")";
                hql2 += " and (" + tree.getTreeCondition() + ")";
            }
            session.createQuery(hql1).setParameter("myPosition", myPosition).executeUpdate();
            session.createQuery(hql2).setParameter("myPosition", myPosition).executeUpdate();
        } else {
            // 否则查找最大的右边位置
            String hql = "select max(bean." + tree.getRgtName() + ") from " + beanName + " bean";
            if (!StringUtils.isBlank(tree.getTreeCondition())) {
                hql += " where " + tree.getTreeCondition();
            }
            Number myPositionNumber = (Number) session.createQuery(hql).uniqueResult();
            // 如不存在,则为0
            if (myPositionNumber == null) {
                myPosition = 1;
            } else {
                myPosition = myPositionNumber.intValue() + 1;
            }
        }
        session.setFlushMode(model);
        for (int i = 0; i < propertyNames.length; i++) {
            if (propertyNames[i].equals(tree.getLftName())) {
                state[i] = myPosition;
            }
            if (propertyNames[i].equals(tree.getRgtName())) {
                state[i] = myPosition + 1;
            }
        }
        return true;
    }
    return false;
}

19 View Complete Implementation : TreeIntercptor.java
Copyright GNU General Public License v2.0
Author : caipiao
@Override
public void onDelete(Object enreplacedy, Serializable id, Object[] state, String[] propertyNames, Type[] types) {
    if (enreplacedy instanceof HibernateTree) {
        HibernateTree<?> tree = (HibernateTree<?>) enreplacedy;
        String beanName = tree.getClreplaced().getName();
        Session session = getSession();
        FlushMode model = session.getFlushMode();
        session.setFlushMode(FlushMode.MANUAL);
        String hql = "select bean." + tree.getLftName() + " from " + beanName + " bean where bean.id=:id";
        Integer myPosition = ((Number) session.createQuery(hql).setParameter("id", tree.getId()).uniqueResult()).intValue();
        String hql1 = "update " + beanName + " bean set bean." + tree.getRgtName() + " = bean." + tree.getRgtName() + " - 2 WHERE bean." + tree.getRgtName() + " > :myPosition";
        String hql2 = "update " + beanName + " bean set bean." + tree.getLftName() + " = bean." + tree.getLftName() + " - 2 WHERE bean." + tree.getLftName() + " > :myPosition";
        if (!StringUtils.isBlank(tree.getTreeCondition())) {
            hql1 += " and (" + tree.getTreeCondition() + ")";
            hql2 += " and (" + tree.getTreeCondition() + ")";
        }
        session.createQuery(hql1).setInteger("myPosition", myPosition).executeUpdate();
        session.createQuery(hql2).setInteger("myPosition", myPosition).executeUpdate();
        session.setFlushMode(model);
    }
}

19 View Complete Implementation : SessionFactoryUtils.java
Copyright Apache License 2.0
Author : langtianya
/**
 * 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 enreplacedyInterceptor Hibernate enreplacedy 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
 * @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 enreplacedyInterceptor, SQLExceptionTranslator jdbcExceptionTranslator, boolean allowCreate) throws HibernateException, IllegalStateException {
    replacedert.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 replacedume 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 = (enreplacedyInterceptor != null ? sessionFactory.openSession(enreplacedyInterceptor) : 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;
}

18 View Complete Implementation : HibernateTransactionManager.java
Copyright MIT License
Author : codeEngraver
@Override
@SuppressWarnings("deprecation")
protected void doCleanupAfterCompletion(Object transaction) {
    HibernateTransactionObject txObject = (HibernateTransactionObject) transaction;
    // Remove the session holder from the thread.
    if (txObject.isNewSessionHolder()) {
        TransactionSynchronizationManager.unbindResource(obtainSessionFactory());
    }
    // Remove the JDBC connection holder from the thread, if exposed.
    if (getDataSource() != null) {
        TransactionSynchronizationManager.unbindResource(getDataSource());
    }
    Session session = txObject.getSessionHolder().getSession();
    if (this.prepareConnection && isPhysicallyConnected(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();
            Integer previousHoldability = txObject.getPreviousHoldability();
            if (previousHoldability != null) {
                con.setHoldability(previousHoldability);
            }
            DataSourceUtils.resetConnectionAfterTransaction(con, txObject.getPreviousIsolationLevel());
        } catch (HibernateException ex) {
            logger.debug("Could not access JDBC Connection of Hibernate Session", ex);
        } catch (Throwable ex) {
            logger.debug("Could not reset JDBC Connection after transaction", 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.allowResultAccessAfterCompletion && !this.hibernateManagedSession) {
            disconnectOnCompletion(session);
        }
    }
    txObject.getSessionHolder().clear();
}

18 View Complete Implementation : OpenSessionInViewFilter.java
Copyright MIT License
Author : codeEngraver
/**
 * 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 FlushMode#MANUAL
 */
@SuppressWarnings("deprecation")
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);
    }
}

18 View Complete Implementation : HibernateTransactionManager.java
Copyright Apache License 2.0
Author : langtianya
@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.");
    }
    Session session = null;
    try {
        if (txObject.getSessionHolder() == null || txObject.getSessionHolder().isSynchronizedWithTransaction()) {
            Interceptor enreplacedyInterceptor = getEnreplacedyInterceptor();
            Session newSession = (enreplacedyInterceptor != null ? getSessionFactory().openSession(enreplacedyInterceptor) : 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_clreplaced' 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);
    }
}

18 View Complete Implementation : HibernateTransactionManager.java
Copyright Apache License 2.0
Author : langtianya
@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();
}

18 View Complete Implementation : OpenSessionInViewFilter.java
Copyright Apache License 2.0
Author : langtianya
/**
 * 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);
    }
}

18 View Complete Implementation : OpenSessionInViewFilter.java
Copyright Apache License 2.0
Author : langtianya
/**
 * 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 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);
    }
}

18 View Complete Implementation : HibernateTransactionManager.java
Copyright Apache License 2.0
Author : spring-projects
@Override
@SuppressWarnings("deprecation")
protected void doCleanupAfterCompletion(Object transaction) {
    HibernateTransactionObject txObject = (HibernateTransactionObject) transaction;
    // Remove the session holder from the thread.
    if (txObject.isNewSessionHolder()) {
        TransactionSynchronizationManager.unbindResource(obtainSessionFactory());
    }
    // Remove the JDBC connection holder from the thread, if exposed.
    if (getDataSource() != null) {
        TransactionSynchronizationManager.unbindResource(getDataSource());
    }
    Session session = txObject.getSessionHolder().getSession();
    if (this.prepareConnection && isPhysicallyConnected(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();
            Integer previousHoldability = txObject.getPreviousHoldability();
            if (previousHoldability != null) {
                con.setHoldability(previousHoldability);
            }
            DataSourceUtils.resetConnectionAfterTransaction(con, txObject.getPreviousIsolationLevel(), txObject.isReadOnly());
        } catch (HibernateException ex) {
            logger.debug("Could not access JDBC Connection of Hibernate Session", ex);
        } catch (Throwable ex) {
            logger.debug("Could not reset JDBC Connection after transaction", 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.allowResultAccessAfterCompletion && !this.hibernateManagedSession) {
            disconnectOnCompletion(session);
        }
    }
    txObject.getSessionHolder().clear();
}

18 View Complete Implementation : HibernateTransactionHelper.java
Copyright Apache License 2.0
Author : webdsl
public static void rollbackAndStartNewTransaction() {
    Session hibSession = HibernateUtil.getCurrentSession();
    Transaction existingTransaction = hibSession.getTransaction();
    try {
        existingTransaction.rollback();
    } catch (Exception ex) {
        org.webdsl.logging.Logger.error(ex);
        ex.printStackTrace();
        existingTransaction.rollback();
    } finally {
        Session newSession = ThreadLocalPage.get().openNewTransactionThroughGetCurrentSession();
        newSession.setFlushMode(FlushMode.COMMIT);
        ThreadLocalPage.get().clearEnreplacediesToBeValidated();
        ThreadLocalPage.get().initVarsAndArgs();
    }
}

18 View Complete Implementation : BeangleSessionContext.java
Copyright GNU Lesser General Public License v3.0
Author : beangle
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();
}

18 View Complete Implementation : Main.java
Copyright GNU Lesser General Public License v2.1
Author : cacheonix
/**
 * Demonstrates HQL with runtime fetch strategy
 */
public void viewAllAuctionsSlow() throws Exception {
    System.out.println("Viewing all auction item objects");
    Session s = factory.openSession();
    Transaction tx = null;
    try {
        // entirely optional!!
        s.setFlushMode(FlushMode.NEVER);
        tx = s.beginTransaction();
        List auctions = s.createQuery("from AuctionItem item " + "left join fetch item.bids bid left join fetch bid.bidder " + "order by item.ends desc").setMaxResults(100).list();
        Iterator iter = new HashSet(auctions).iterator();
        while (iter.hasNext()) {
            AuctionItem auction = (AuctionItem) iter.next();
            System.out.println("Auction: " + auction.getId() + " - " + auction.getDescription() + ", ends: " + auction.getEnds() + ", bids: " + auction.getBids());
        }
        System.out.println();
        tx.commit();
    } catch (Exception e) {
        if (tx != null)
            tx.rollback();
        throw e;
    } finally {
        s.close();
    }
}

18 View Complete Implementation : TreeIntercptor.java
Copyright GNU General Public License v2.0
Author : caipiao
private boolean updateParent(HibernateTree<?> tree, HibernateTree<?> preParent, HibernateTree<?> currParent) {
    // 都为空、或都不为空且相等时,不作处理
    if ((preParent == null && currParent == null) || (preParent != null && currParent != null && preParent.getId().equals(currParent.getId()))) {
        return false;
    }
    String beanName = tree.getClreplaced().getName();
    if (log.isDebugEnabled()) {
        log.debug("update Tree {}, id={}, " + "pre-parent id={}, curr-parent id={}", new Object[] { beanName, tree.getId(), preParent == null ? null : preParent.getId(), currParent == null ? null : currParent.getId() });
    }
    Session session = getSession();
    // 保存刷新模式,并设置成手动刷新
    FlushMode model = session.getFlushMode();
    session.setFlushMode(FlushMode.MANUAL);
    // 先空出位置。当前父节点存在时,才需要空出位置。
    Integer currParentRgt;
    if (currParent != null) {
        // 获得节点跨度
        String hql = "select bean." + tree.getLftName() + ",bean." + tree.getRgtName() + " from " + beanName + " bean where bean.id=:id";
        Object[] position = (Object[]) session.createQuery(hql).setParameter("id", tree.getId()).uniqueResult();
        int nodeLft = ((Number) position[0]).intValue();
        int nodeRgt = ((Number) position[1]).intValue();
        int span = nodeRgt - nodeLft + 1;
        log.debug("current node span={}", span);
        // 获得当前父节点右位置
        Object[] currPosition = (Object[]) session.createQuery(hql).setParameter("id", currParent.getId()).uniqueResult();
        int currParentLft = ((Number) currPosition[0]).intValue();
        currParentRgt = ((Number) currPosition[1]).intValue();
        log.debug("current parent lft={} rgt={}", currParentLft, currParentRgt);
        // 空出位置
        String hql1 = "update " + beanName + " bean set bean." + tree.getRgtName() + " = bean." + tree.getRgtName() + " + " + span + " WHERE bean." + tree.getRgtName() + " >= :parentRgt";
        String hql2 = "update " + beanName + " bean set bean." + tree.getLftName() + " = bean." + tree.getLftName() + " + " + span + " WHERE bean." + tree.getLftName() + " >= :parentRgt";
        if (!StringUtils.isBlank(tree.getTreeCondition())) {
            hql1 += " and (" + tree.getTreeCondition() + ")";
            hql2 += " and (" + tree.getTreeCondition() + ")";
        }
        session.createQuery(hql1).setInteger("parentRgt", currParentRgt).executeUpdate();
        session.createQuery(hql2).setInteger("parentRgt", currParentRgt).executeUpdate();
        log.debug("vacated span hql: {}, {}, parentRgt={}", new Object[] { hql1, hql2, currParentRgt });
    } else {
        // 否则查找最大的右边位置
        String hql = "select max(bean." + tree.getRgtName() + ") from " + beanName + " bean";
        if (!StringUtils.isBlank(tree.getTreeCondition())) {
            hql += " where " + tree.getTreeCondition();
        }
        currParentRgt = ((Number) session.createQuery(hql).uniqueResult()).intValue();
        currParentRgt++;
        log.debug("max node left={}", currParentRgt);
    }
    // 再调整自己
    String hql = "select bean." + tree.getLftName() + ",bean." + tree.getRgtName() + " from " + beanName + " bean where bean.id=:id";
    Object[] position = (Object[]) session.createQuery(hql).setParameter("id", tree.getId()).uniqueResult();
    int nodeLft = ((Number) position[0]).intValue();
    int nodeRgt = ((Number) position[1]).intValue();
    int span = nodeRgt - nodeLft + 1;
    if (log.isDebugEnabled()) {
        log.debug("before adjust self left={} right={} span={}", new Object[] { nodeLft, nodeRgt, span });
    }
    int offset = currParentRgt - nodeLft;
    hql = "update " + beanName + " bean set bean." + tree.getLftName() + "=bean." + tree.getLftName() + "+:offset, bean." + tree.getRgtName() + "=bean." + tree.getRgtName() + "+:offset WHERE bean." + tree.getLftName() + " between :nodeLft and :nodeRgt";
    if (!StringUtils.isBlank(tree.getTreeCondition())) {
        hql += " and (" + tree.getTreeCondition() + ")";
    }
    session.createQuery(hql).setParameter("offset", offset).setParameter("nodeLft", nodeLft).setParameter("nodeRgt", nodeRgt).executeUpdate();
    if (log.isDebugEnabled()) {
        log.debug("adjust self hql: {}, offset={}, nodeLft={}, nodeRgt={}", new Object[] { hql, offset, nodeLft, nodeRgt });
    }
    // 最后删除(清空位置)
    String hql1 = "update " + beanName + " bean set bean." + tree.getRgtName() + " = bean." + tree.getRgtName() + " - " + span + " WHERE bean." + tree.getRgtName() + " > :nodeRgt";
    String hql2 = "update " + beanName + " bean set bean." + tree.getLftName() + " = bean." + tree.getLftName() + " - " + span + " WHERE bean." + tree.getLftName() + " > :nodeRgt";
    if (!StringUtils.isBlank(tree.getTreeCondition())) {
        hql1 += " and (" + tree.getTreeCondition() + ")";
        hql2 += " and (" + tree.getTreeCondition() + ")";
    }
    session.createQuery(hql1).setParameter("nodeRgt", nodeRgt).executeUpdate();
    session.createQuery(hql2).setParameter("nodeRgt", nodeRgt).executeUpdate();
    if (log.isDebugEnabled()) {
        log.debug("clear span hql1:{}, hql2:{}, nodeRgt:{}", new Object[] { hql1, hql2, nodeRgt });
    }
    session.setFlushMode(model);
    return true;
}

17 View Complete Implementation : HibernateTransactionManager.java
Copyright GNU Lesser General Public License v3.0
Author : beangle
@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()) {
        SessionUtils.closeSession(session);
    } else {
        if (txObject.getSessionHolder().getPreviousFlushMode() != null) {
            session.setFlushMode(txObject.getSessionHolder().getPreviousFlushMode());
        }
        if (!this.hibernateManagedSession)
            session.disconnect();
    }
    txObject.getSessionHolder().clear();
}

17 View Complete Implementation : HibernateTransactionManager.java
Copyright GNU Lesser General Public License v3.0
Author : beangle
@Override
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.");
    }
    Session session = null;
    try {
        if (txObject.getSessionHolder() == null || txObject.getSessionHolder().isSynchronizedWithTransaction()) {
            Session newSession = getSessionFactory().openSession();
            txObject.setSession(newSession);
        }
        session = txObject.getSessionHolder().getSession();
        if (this.prepareConnection && isSameConnectionForEntireSession(session)) {
            // We're allowed to change the transaction settings of the JDBC Connection.
            Connection con = ((SessionImplementor) 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' (BeangleTransactionFactory's default). " + "Make sure that your SessionFactoryBean actually uses BeangleTransactionFactory: Your " + "Hibernate properties should *not* include a 'hibernate.transaction.factory_clreplaced' property!");
            }
        }
        if (definition.isReadOnly() && txObject.isNewSession()) {
            // Just set to NEVER 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.isManualFlushMode(session.getFlushMode())) {
                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 = ((SessionImplementor) 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 (Exception 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 {
                SessionUtils.closeSession(session);
            }
        }
        throw new CannotCreateTransactionException("Could not open Hibernate Session for transaction", ex);
    }
}

17 View Complete Implementation : SpringSessionContext.java
Copyright MIT License
Author : codeEngraver
/**
 * Retrieve the Spring-managed Session for the current thread, if any.
 */
@Override
@SuppressWarnings("deprecation")
public Session currentSession() throws HibernateException {
    Object value = TransactionSynchronizationManager.getResource(this.sessionFactory);
    if (value instanceof Session) {
        return (Session) value;
    } else if (value instanceof SessionHolder) {
        // HibernateTransactionManager
        SessionHolder sessionHolder = (SessionHolder) value;
        Session session = sessionHolder.getSession();
        if (!sessionHolder.isSynchronizedWithTransaction() && TransactionSynchronizationManager.isSynchronizationActive()) {
            TransactionSynchronizationManager.registerSynchronization(new SpringSessionSynchronization(sessionHolder, this.sessionFactory, false));
            sessionHolder.setSynchronizedWithTransaction(true);
            // Switch to FlushMode.AUTO, as we have to replacedume a thread-bound Session
            // with FlushMode.MANUAL, which needs to allow flushing within the transaction.
            FlushMode flushMode = SessionFactoryUtils.getFlushMode(session);
            if (flushMode.equals(FlushMode.MANUAL) && !TransactionSynchronizationManager.isCurrentTransactionReadOnly()) {
                session.setFlushMode(FlushMode.AUTO);
                sessionHolder.setPreviousFlushMode(flushMode);
            }
        }
        return session;
    } else if (value instanceof EnreplacedyManagerHolder) {
        // JpaTransactionManager
        return ((EnreplacedyManagerHolder) value).getEnreplacedyManager().unwrap(Session.clreplaced);
    }
    if (this.transactionManager != null && this.jtaSessionContext != null) {
        try {
            if (this.transactionManager.getStatus() == Status.STATUS_ACTIVE) {
                Session session = this.jtaSessionContext.currentSession();
                if (TransactionSynchronizationManager.isSynchronizationActive()) {
                    TransactionSynchronizationManager.registerSynchronization(new SpringFlushSynchronization(session));
                }
                return session;
            }
        } catch (SystemException ex) {
            throw new HibernateException("JTA TransactionManager found but status check failed", ex);
        }
    }
    if (TransactionSynchronizationManager.isSynchronizationActive()) {
        Session session = this.sessionFactory.openSession();
        if (TransactionSynchronizationManager.isCurrentTransactionReadOnly()) {
            session.setFlushMode(FlushMode.MANUAL);
        }
        SessionHolder sessionHolder = new SessionHolder(session);
        TransactionSynchronizationManager.registerSynchronization(new SpringSessionSynchronization(sessionHolder, this.sessionFactory, true));
        TransactionSynchronizationManager.bindResource(this.sessionFactory, sessionHolder);
        sessionHolder.setSynchronizedWithTransaction(true);
        return session;
    } else {
        throw new HibernateException("Could not obtain transaction-synchronized Session for current thread");
    }
}

17 View Complete Implementation : SpringSessionSynchronization.java
Copyright MIT License
Author : codeEngraver
@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;
        }
    }
}

17 View Complete Implementation : HibernateObsDAO.java
Copyright Apache License 2.0
Author : isstac
/**
 * @see org.openmrs.api.db.ObsDAO#getSavedStatus(org.openmrs.Obs)
 */
@Override
public Obs.Status getSavedStatus(Obs obs) {
    // avoid premature flushes when this internal method is called from inside a service method
    Session session = sessionFactory.getCurrentSession();
    FlushMode flushMode = session.getFlushMode();
    session.setFlushMode(FlushMode.MANUAL);
    try {
        SQLQuery sql = session.createSQLQuery("select status from obs where obs_id = :obsId");
        sql.setInteger("obsId", obs.getObsId());
        return Obs.Status.valueOf((String) sql.uniqueResult());
    } finally {
        session.setFlushMode(flushMode);
    }
}

17 View Complete Implementation : HibernateInterceptor.java
Copyright Apache License 2.0
Author : langtianya
@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());
            }
        }
    }
}

17 View Complete Implementation : SpringSessionSynchronization.java
Copyright Apache License 2.0
Author : langtianya
@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;
            }
            // 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();
        }
    }
}

17 View Complete Implementation : HibernateTransactionManager.java
Copyright Apache License 2.0
Author : langtianya
@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();
            Integer previousHoldability = txObject.getPreviousHoldability();
            if (previousHoldability != null) {
                con.setHoldability(previousHoldability);
            }
            DataSourceUtils.resetConnectionAfterTransaction(con, txObject.getPreviousIsolationLevel());
        } catch (HibernateException ex) {
            logger.debug("Could not access JDBC Connection of Hibernate Session", ex);
        } catch (Throwable ex) {
            logger.debug("Could not reset JDBC Connection after transaction", 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.allowResultAccessAfterCompletion && !this.hibernateManagedSession) {
            disconnectOnCompletion(session);
        }
    }
    txObject.getSessionHolder().clear();
}

17 View Complete Implementation : SpringSessionContext.java
Copyright Apache License 2.0
Author : langtianya
/**
 * Retrieve the Spring-managed Session for the current thread, if any.
 */
@Override
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 (!sessionHolder.isSynchronizedWithTransaction() && TransactionSynchronizationManager.isSynchronizationActive()) {
            TransactionSynchronizationManager.registerSynchronization(new SpringSessionSynchronization(sessionHolder, this.sessionFactory, false));
            sessionHolder.setSynchronizedWithTransaction(true);
            // Switch to FlushMode.AUTO, as we have to replacedume a thread-bound Session
            // with FlushMode.MANUAL, which needs to allow flushing within the transaction.
            FlushMode flushMode = session.getFlushMode();
            if (flushMode.equals(FlushMode.MANUAL) && !TransactionSynchronizationManager.isCurrentTransactionReadOnly()) {
                session.setFlushMode(FlushMode.AUTO);
                sessionHolder.setPreviousFlushMode(flushMode);
            }
        }
        return session;
    }
    if (this.transactionManager != null) {
        try {
            if (this.transactionManager.getStatus() == Status.STATUS_ACTIVE) {
                Session session = this.jtaSessionContext.currentSession();
                if (TransactionSynchronizationManager.isSynchronizationActive()) {
                    TransactionSynchronizationManager.registerSynchronization(new SpringFlushSynchronization(session));
                }
                return session;
            }
        } catch (SystemException ex) {
            throw new HibernateException("JTA TransactionManager found but status check failed", ex);
        }
    }
    if (TransactionSynchronizationManager.isSynchronizationActive()) {
        Session session = this.sessionFactory.openSession();
        if (TransactionSynchronizationManager.isCurrentTransactionReadOnly()) {
            session.setFlushMode(FlushMode.MANUAL);
        }
        SessionHolder sessionHolder = new SessionHolder(session);
        TransactionSynchronizationManager.registerSynchronization(new SpringSessionSynchronization(sessionHolder, this.sessionFactory, true));
        TransactionSynchronizationManager.bindResource(this.sessionFactory, sessionHolder);
        sessionHolder.setSynchronizedWithTransaction(true);
        return session;
    } else {
        throw new HibernateException("Could not obtain transaction-synchronized Session for current thread");
    }
}

17 View Complete Implementation : SpringSessionSynchronization.java
Copyright Apache License 2.0
Author : langtianya
@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;
        }
    }
}

17 View Complete Implementation : HibernateTransactionManager.java
Copyright Apache License 2.0
Author : langtianya
@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 && isPhysicallyConnected(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();
            Integer previousHoldability = txObject.getPreviousHoldability();
            if (previousHoldability != null) {
                con.setHoldability(previousHoldability);
            }
            DataSourceUtils.resetConnectionAfterTransaction(con, txObject.getPreviousIsolationLevel());
        } catch (HibernateException ex) {
            logger.debug("Could not access JDBC Connection of Hibernate Session", ex);
        } catch (Throwable ex) {
            logger.debug("Could not reset JDBC Connection after transaction", 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.allowResultAccessAfterCompletion && !this.hibernateManagedSession) {
            disconnectOnCompletion(session);
        }
    }
    txObject.getSessionHolder().clear();
}