Example usage for org.hibernate FlushMode isManualFlushMode

List of usage examples for org.hibernate FlushMode isManualFlushMode

Introduction

In this page you can find the example usage for org.hibernate FlushMode isManualFlushMode.

Prototype

@Deprecated
public static boolean isManualFlushMode(FlushMode mode) 

Source Link

Document

Checks to see if the given mode is the same as #MANUAL .

Usage

From source file:com.byteslounge.spring.tx.MyOwnTxManager.java

License:Apache License

@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.");
    }//from  w w  w. j ava 2  s . c  om

    Session session = null;

    try {
        if (txObject.getSessionHolder() == null
                || txObject.getSessionHolder().isSynchronizedWithTransaction()) {
            Session newSession = getSessionFactory().openSession();
            if (logger.isDebugEnabled()) {
                logger.debug("Opened new Session [" + 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 [" + session + "]");
            }
            Connection con = ((SessionImplementor) session).connection();
            if (con.isClosed()) {
                System.out.println("Connection closed by exception");
            }
            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).");
            }
            if (logger.isDebugEnabled()) {
                logger.debug("Not preparing JDBC Connection of Hibernate Session [" + session + "]");
            }
        }

        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 {
                SessionFactoryUtils.closeSession(session);
            }
        }
        throw new CannotCreateTransactionException("Could not open Hibernate Session for transaction", ex);
    }
}

From source file:com.googlecode.hibernate.audit.synchronization.AuditSynchronization.java

License:Open Source License

public void doBeforeTransactionCompletion(SessionImplementor session) {
    if (workUnits.size() == 0) {
        return;/*w w w .ja  v a  2 s. c o  m*/
    }
    if (!isMarkedForRollback(auditedSession)) {
        try {
            if (FlushMode.isManualFlushMode(auditedSession.getFlushMode())) {
                Session temporarySession = null;
                try {
                    temporarySession = ((Session) session).sessionWithOptions().transactionContext()
                            .autoClose(false).connectionReleaseMode(ConnectionReleaseMode.AFTER_TRANSACTION)
                            .openSession();
                    executeInSession(temporarySession);
                    temporarySession.flush();
                } finally {
                    if (temporarySession != null) {
                        temporarySession.close();
                    }
                }
            } else {
                auditedSession.flush();
                executeInSession(auditedSession);
            }
        } catch (RuntimeException e) {
            if (log.isErrorEnabled()) {
                log.error("RuntimeException occurred in beforeCompletion, will rollback and re-throw exception",
                        e);
            }
            rollback();
            throw e;
        }
    }
}

From source file:com.googlecode.hibernate.audit.synchronization.AuditSynchronization.java

License:Open Source License

private void executeInSession(Session session) {
    if (log.isDebugEnabled()) {
        log.debug("executeInSession begin");
    }//from w ww  .j  a va  2  s .  c  o  m

    try {
        AuditWorkUnit workUnit;
        SortedSet<AuditLogicalGroup> auditLogicalGroups = new TreeSet<AuditLogicalGroup>(
                new Comparator<AuditLogicalGroup>() {
                    // sort audit logical groups in order to minimize
                    // database dead lock conditions.
                    public int compare(AuditLogicalGroup o1, AuditLogicalGroup o2) {
                        // note that both entities should already be
                        // persistent so they must have ids
                        return o1.getId().compareTo(o2.getId());
                    };
                });

        AuditTransaction auditTransaction = new AuditTransaction();
        auditTransaction.setTimestamp(new Date());
        Principal principal = auditConfiguration.getExtensionManager().getSecurityInformationProvider()
                .getPrincipal();
        auditTransaction.setUsername(principal == null ? null : principal.getName());

        if (log.isDebugEnabled()) {
            log.debug("start workUnits perform");
        }
        while ((workUnit = workUnits.poll()) != null) {
            workUnit.perform(session, auditConfiguration, auditTransaction);
            auditLogicalGroups.addAll(workUnit.getAuditLogicalGroups());
        }
        if (log.isDebugEnabled()) {
            log.debug("end workUnits perform");
        }

        List<AuditTransactionAttribute> attributes = auditConfiguration.getExtensionManager()
                .getAuditTransactionAttributeProvider().getAuditTransactionAttributes(session);

        if (attributes != null && !attributes.isEmpty()) {
            for (AuditTransactionAttribute attribute : attributes) {
                attribute.setAuditTransaction(auditTransaction);
            }
            auditTransaction.getAuditTransactionAttributes().addAll(attributes);
        }

        concurrencyModificationCheck(session, auditLogicalGroups, auditTransaction);

        session.save(auditTransaction);
        for (AuditLogicalGroup storedAuditLogicalGroup : auditLogicalGroups) {
            storedAuditLogicalGroup.setLastUpdatedAuditTransactionId(auditTransaction.getId());
        }

        if (!FlushMode.isManualFlushMode(session.getFlushMode())) {
            session.flush();
        }
    } finally {
        if (log.isDebugEnabled()) {
            log.debug("executeInSession end");
        }
    }
}

From source file:itensil.io.HibernateUtil.java

License:Open Source License

/**
 * Is this a read-only session?//from  w  w  w  .  j av a 2s .  co m
 * @return true if read-only
 */
public static boolean isReadOnlySession() {
    return FlushMode.isManualFlushMode(getSession().getFlushMode());
}

From source file:org.babyfish.springframework.orm.hibernate.SpringXSessionContext.java

License:Open Source License

/**
 * Retrieve the Spring-managed Session for the current thread, if any.
 *///from   w  w w  . j  av  a 2s .  c  o m
@SuppressWarnings("deprecation")
public XSession currentSession() throws HibernateException {
    Object value = TransactionSynchronizationManager.getResource(this.sessionFactory);
    if (value instanceof XSession) {
        return (XSession) value;
    } else if (value instanceof SessionHolder) {
        SessionHolder sessionHolder = (SessionHolder) value;
        XSession session = (XSession) sessionHolder.getSession();
        if (TransactionSynchronizationManager.isSynchronizationActive()
                && !sessionHolder.isSynchronizedWithTransaction()) {
            TransactionSynchronizationManager.registerSynchronization(
                    new SpringSessionSynchronization(sessionHolder, this.sessionFactory));
            sessionHolder.setSynchronizedWithTransaction(true);
            // Switch to FlushMode.AUTO, as we have to assume a thread-bound Session
            // with FlushMode.MANUAL, which needs to allow flushing within the transaction.
            FlushMode flushMode = session.getFlushMode();
            if (FlushMode.isManualFlushMode(flushMode)
                    && !TransactionSynchronizationManager.isCurrentTransactionReadOnly()) {
                session.setFlushMode(FlushMode.AUTO);
                sessionHolder.setPreviousFlushMode(flushMode);
            }
        }
        return session;
    } else if (this.jtaSessionContext != null) {
        XSession session = this.jtaSessionContext.currentSession();
        if (TransactionSynchronizationManager.isSynchronizationActive()) {
            TransactionSynchronizationManager.registerSynchronization(new SpringFlushSynchronization(session));
        }
        return session;
    } else {
        throw new HibernateException("No Session found for current thread");
    }
}

From source file:org.beangle.orm.hibernate.BeangleSessionContext.java

License:Open Source License

/**
 * Retrieve the Spring-managed Session for the current thread, if any.
 *///w  w w. j  a v a  2 s.  c o  m
public Session currentSession() throws HibernateException {
    SessionHolder sessionHolder = SessionUtils.currentSession(this.sessionFactory);
    Session session = sessionHolder.getSession();
    // TODO what time enter into the code?
    if (TransactionSynchronizationManager.isSynchronizationActive()
            && !sessionHolder.isSynchronizedWithTransaction()) {
        TransactionSynchronizationManager
                .registerSynchronization(new SessionSynchronization(sessionHolder, this.sessionFactory));
        sessionHolder.setSynchronizedWithTransaction(true);
        // Switch to FlushMode.AUTO, as we have to assume a thread-bound Session
        // with FlushMode.MANUAL, which needs to allow flushing within the transaction.
        FlushMode flushMode = session.getFlushMode();
        if (FlushMode.isManualFlushMode(flushMode)
                && !TransactionSynchronizationManager.isCurrentTransactionReadOnly()) {
            session.setFlushMode(FlushMode.AUTO);
            sessionHolder.setPreviousFlushMode(flushMode);
        }
    }
    return session;
}

From source file:org.beangle.orm.hibernate.BeangleSessionContext.java

License:Open Source License

public void beforeCommit(boolean readOnly) throws DataAccessException {
    if (!readOnly) {
        Session session = getCurrentSession();
        // Read-write transaction -> flush the Hibernate Session.
        // Further check: only flush when not FlushMode.MANUAL.
        if (!FlushMode.isManualFlushMode(session.getFlushMode())) {
            try {
                session.flush();/*w w w.ja v  a 2 s  .c om*/
            } catch (HibernateException ex) {
                throw SessionUtils.convertHibernateAccessException(ex);
            }
        }
    }
}

From source file:org.beangle.orm.hibernate.HibernateTransactionManager.java

License:Open Source License

@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.");
    }//from   w  w w  . ja  v  a  2s. com

    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_class' 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);
    }
}

From source file:org.codehaus.groovy.grails.orm.hibernate.GrailsSessionContext.java

License:Apache License

/**
 * Retrieve the Spring-managed Session for the current thread, if any.
 *///  w w  w  . ja va  2s  .  c o  m
public Session currentSession() throws HibernateException {
    Object value = TransactionSynchronizationManager.getResource(sessionFactory);
    if (value instanceof Session) {
        return (Session) value;
    }

    if (value instanceof SessionHolder) {
        SessionHolder sessionHolder = (SessionHolder) value;
        Session session = sessionHolder.getSession();
        if (TransactionSynchronizationManager.isSynchronizationActive()
                && !sessionHolder.isSynchronizedWithTransaction()) {
            TransactionSynchronizationManager
                    .registerSynchronization(createSpringSessionSynchronization(sessionHolder));
            sessionHolder.setSynchronizedWithTransaction(true);
            // Switch to FlushMode.AUTO, as we have to assume a thread-bound Session
            // with FlushMode.MANUAL, which needs to allow flushing within the transaction.
            FlushMode flushMode = session.getFlushMode();
            if (FlushMode.isManualFlushMode(flushMode)
                    && !TransactionSynchronizationManager.isCurrentTransactionReadOnly()) {
                session.setFlushMode(FlushMode.AUTO);
                sessionHolder.setPreviousFlushMode(flushMode);
            }
        }
        return session;
    }

    if (jtaSessionContext != null) {
        Session session = jtaSessionContext.currentSession();
        if (TransactionSynchronizationManager.isSynchronizationActive()) {
            TransactionSynchronizationManager
                    .registerSynchronization(createSpringFlushSynchronization(session));
        }
        return session;
    }

    if (allowCreate) {
        // be consistent with older HibernateTemplate behavior
        return createSession(value);
    }

    throw new HibernateException("No Session found for current thread");
}

From source file:org.grails.orm.hibernate.support.FlushOnRedirectEventListener.java

License:Apache License

public void responseRedirected(String url) {
    datastore.getHibernateTemplate().execute(new Closure<Object>(this) {
        @Override/*ww w .j  a va2 s.  c  o  m*/
        public Object call(Object... args) {
            Session session = (Session) args[0];
            if (!FlushMode.isManualFlushMode(session.getFlushMode())) {
                session.flush();
            }
            return null;
        }
    });
}