Example usage for org.hibernate FlushMode AUTO

List of usage examples for org.hibernate FlushMode AUTO

Introduction

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

Prototype

FlushMode AUTO

To view the source code for org.hibernate FlushMode AUTO.

Click Source Link

Document

The Session is sometimes flushed before query execution in order to ensure that queries never return stale state.

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  2s.  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.coedil99.modello_di_dominio.Coedil99PersistentManager.java

private Coedil99PersistentManager() throws PersistentException {
    super(_connectionSetting, _sessionType, _timeToAlive, new String[] {}, _extraProperties,
            _configurationFile);/*from  w  w w  .ja v a2s.  co m*/
    setFlushMode(FlushMode.AUTO);
}

From source file:com.denksoft.springstarter.util.HibernateFilter.java

License:Open Source License

@Override
protected Session getSession(SessionFactory sessionFactory) throws DataAccessResourceFailureException {
    //        Session session = SessionFactoryUtils.getSession(sessionFactory, true);
    Session session = super.getSession(sessionFactory);
    //set the FlushMode to auto in order to save objects.
    session.setFlushMode(FlushMode.AUTO);
    return session;
}

From source file:com.heliosapm.aa4h.parser.XMLQueryParser.java

License:Apache License

/**
 * Initializes a Criteria Query.//from www  .  j  ava  2 s  .c  o m
 * Mandatory Attributes:<ul>
 * <li><b>name</b>: The unqualified class name driving the criteria query.</li>
 * </ul>
 * Optional Attributes:<ul>
 * <li><b>prefix</b>: The package name of the class driving the criteria query. If null, no package is assumed.</li>
 * <li><b>maxSize</b>: The maximum number of rows to return from the database.</li>
 * <li><b>fetchSize</b>: The number of rows to fetch when rows are requested. Usually not useful for AA4H.</li>
 * <li><b>cacheEnabled</b>: Enables or disables caching for the queried objects.</li>
 * <li><b>cacheMode</b>: The cache options for the queried objects.</li>
 * <li><b>flushMode</b>: The session flush options.</li>
 * <li><b>fetchMode</b>: The collection fetch options for the query.</li>
 * <li><b>lockMode</b>: The row lock options for the queried rows.</li>
 * <li><b>timeOut</b>: The query timeout option.</li>
 * <li><b>rowCountOnly</b>: Returns a count of the query rows only.</li>
 * </ul>
 * @param attrs The attributes of the processed node.
 * @return An appended or new CriteriaSpecification
 * @throws SAXException
 */
protected CriteriaSpecification processCriteria(Attributes attrs) throws SAXException {
    if (inDetached) {
        return criteriaStack.peek();
    }
    String name = attrs.getValue("name");
    String prefix = attrs.getValue("prefix");
    if (prefix != null) {
        className = prefix + "." + name;
    } else {
        className = name;
    }
    String maxSize = attrs.getValue("maxSize");
    String fetchSize = attrs.getValue("fetchSize");
    String firstResult = attrs.getValue("firstResult");
    String cacheEnabled = attrs.getValue("cacheEnabled");
    String cacheMode = attrs.getValue("cacheMode");
    String flushMode = attrs.getValue("flushMode");
    String fetchMode = attrs.getValue("fetchMode");
    String lockMode = attrs.getValue("lockMode");
    String timeOut = attrs.getValue("timeOut");
    String rowCountOnly = attrs.getValue("rowCountOnly");
    Criteria newCriteria = null;
    try {
        if (criteriaStack.size() == 0) {
            newCriteria = session.createCriteria(className);
        } else {
            newCriteria = ((Criteria) criteriaStack.peek()).createCriteria(className);
        }
        criteriaStack.push(newCriteria);
        if ("true".equalsIgnoreCase(rowCountOnly)) {
            newCriteria.setProjection(Projections.projectionList().add(Projections.rowCount())

            );
            setRowCountOnly(true);
        }
        if (maxSize != null && isRowCountOnly() == false) {
            newCriteria.setMaxResults(Integer.parseInt(maxSize));
        }
        if (fetchSize != null && isRowCountOnly() == false) {
            newCriteria.setFetchSize(Integer.parseInt(fetchSize));
        }
        if (firstResult != null && isRowCountOnly() == false) {
            newCriteria.setFirstResult(Integer.parseInt(firstResult));
        }
        if (timeOut != null) {
            newCriteria.setTimeout(Integer.parseInt(timeOut));
        }

        if ("true".equalsIgnoreCase(cacheEnabled)) {
            newCriteria.setCacheable(true);
        } else if ("false".equalsIgnoreCase(cacheEnabled)) {
            newCriteria.setCacheable(false);
        }
        if (fetchMode != null && fetchMode.length() > 0) {
            if ("JOIN".equalsIgnoreCase(fetchMode)) {
                newCriteria.setFetchMode(name, FetchMode.JOIN);
            } else if ("SELECT".equalsIgnoreCase(fetchMode)) {
                newCriteria.setFetchMode(name, FetchMode.SELECT);
            } else {
                newCriteria.setFetchMode(name, FetchMode.DEFAULT);
            }
        } else {
            newCriteria.setFetchMode(name, FetchMode.DEFAULT);
        }
        if (cacheMode != null && cacheMode.length() > 0) {
            if ("GET".equalsIgnoreCase(cacheMode)) {
                newCriteria.setCacheMode(CacheMode.GET);
            } else if ("IGNORE".equalsIgnoreCase(cacheMode)) {
                newCriteria.setCacheMode(CacheMode.IGNORE);
            } else if ("NORMAL".equalsIgnoreCase(cacheMode)) {
                newCriteria.setCacheMode(CacheMode.NORMAL);
            } else if ("PUT".equalsIgnoreCase(cacheMode)) {
                newCriteria.setCacheMode(CacheMode.PUT);
            } else if ("REFRESH".equalsIgnoreCase(cacheMode)) {
                newCriteria.setCacheMode(CacheMode.REFRESH);
            } else {
                newCriteria.setCacheMode(CacheMode.NORMAL);
            }
        }
        if (lockMode != null && lockMode.length() > 0) {
            if ("NONE".equalsIgnoreCase(lockMode)) {
                newCriteria.setLockMode(LockMode.NONE);
            } else if ("READ".equalsIgnoreCase(lockMode)) {
                newCriteria.setLockMode(LockMode.READ);
            } else if ("UPGRADE".equalsIgnoreCase(lockMode)) {
                newCriteria.setLockMode(LockMode.UPGRADE);
            } else if ("UPGRADE_NOWAIT".equalsIgnoreCase(lockMode)) {
                newCriteria.setLockMode(LockMode.UPGRADE_NOWAIT);
            } else if ("WRITE".equalsIgnoreCase(lockMode)) {
                newCriteria.setLockMode(LockMode.WRITE);
            } else {
                throw new SAXException("lockMode[" + lockMode + "] Not Recognized");
            }
        }
        if (flushMode != null && flushMode.length() > 0) {
            if ("ALWAYS".equalsIgnoreCase(flushMode)) {
                newCriteria.setFlushMode(FlushMode.ALWAYS);
            } else if ("AUTO".equalsIgnoreCase(flushMode)) {
                newCriteria.setFlushMode(FlushMode.AUTO);
            } else if ("COMMIT".equalsIgnoreCase(flushMode)) {
                newCriteria.setFlushMode(FlushMode.COMMIT);
            } else if ("NEVER".equalsIgnoreCase(flushMode)) {
                // NEVER is deprecated, so we won't throw an exception but we'll ignore it.
            } else {
                throw new SAXException("flushMode[" + flushMode + "] Not Recognized");
            }
        }
        return newCriteria;

    } catch (Exception e) {
        throw new SAXException("Unable to configure class " + className, e);
    }
}

From source file:com.miranteinfo.seam.hibernate.HibernateAutoFlushEventListener.java

License:Open Source License

private boolean flushMightBeNeeded(final EventSource source) {
    return !source.getFlushMode().lessThan(FlushMode.AUTO) && source.getDontFlushFromFind() == 0
            && source.getPersistenceContext().hasNonReadOnlyEntities();
}

From source file:com.smi.travel.common.SessionInView.java

@Override
protected Session getSession(SessionFactory sessionFactory) throws DataAccessResourceFailureException {
    Session session = SessionFactoryUtils.getSession(sessionFactory, true);
    session.setFlushMode(FlushMode.AUTO);
    return session;
}

From source file:com.springsource.insight.samples.rest.RestfulRepositoryImplTest.java

License:Apache License

protected void manuallyStartDaoSession() {
    // simulate open session in view
    final SessionFactory sessFac = getSessionFactory();
    if (TransactionSynchronizationManager.hasResource(sessFac)) {
        // Do not modify the Session: just set the participate flag.
        _txParticipating = true;//  w  ww  .j ava 2 s . co m
    } else {
        // NOTE: the session factory interceptor is overridden by an empty one, because the
        // real interceptor may not function correctly in this test-specific setup.
        final Session session = SessionFactoryUtils.getSession(sessFac, EmptyInterceptor.INSTANCE, null);
        session.setFlushMode(FlushMode.AUTO);
        TransactionSynchronizationManager.bindResource(sessFac, new SessionHolder(session));
        logger.info("Started transaction context");
    }
}

From source file:com.wideplay.warp.persist.hibernate.HibernateLocalTxnInterceptor.java

License:Apache License

public Object invoke(MethodInvocation methodInvocation) throws Throwable {
    Session session = sessionProvider.get();

    //allow silent joining of enclosing transactional methods (NOTE: this ignores the current method's txn-al settings)
    if (session.getTransaction().isActive())
        return methodInvocation.proceed();

    //read out transaction settings
    Transactional transactional = readTransactionMetadata(methodInvocation);

    //read-only txn?
    FlushMode savedFlushMode = FlushMode.AUTO;
    if (TransactionType.READ_ONLY.equals(transactional.type()))
        session.setFlushMode(FlushMode.MANUAL);

    try {/*from   ww w. j  a  v a  2  s  .co m*/
        //no transaction already started, so start one and enforce its semantics
        Transaction txn = session.beginTransaction();
        Object result;

        try {
            result = methodInvocation.proceed();

        } catch (Exception e) {

            //commit transaction only if rollback didnt occur
            if (rollbackIfNecessary(transactional, e, txn))
                txn.commit();

            //propagate whatever exception is thrown anyway
            throw e;
        }

        //everything was normal so commit the txn (do not move into try block as it interferes with the advised method's throwing semantics)
        Exception commitException = null;
        try {
            txn.commit();
        } catch (RuntimeException re) {
            txn.rollback();
            commitException = re;
        }

        //propagate anyway
        if (null != commitException)
            throw commitException;

        //or return result
        return result;
    } finally {

        //if read-only txn, then restore flushmode, default is automatic flush
        if (TransactionType.READ_ONLY.equals(transactional.type()))
            session.setFlushMode(savedFlushMode);
    }
}

From source file:corner.orm.tapestry.filter.OneSessionPerServletRequestFilter.java

License:Apache License

/**
 * Get a Session for the SessionFactory that this filter uses. Note that
 * this just applies in single session mode!
 * <p>//from  w  ww  . j  a v  a 2s  .c o m
 * The default implementation delegates to SessionFactoryUtils' getSession
 * method and sets the Session's flushMode to NEVER.
 * <p>
 * Can be overridden in subclasses for creating a Session with a custom
 * entity interceptor or JDBC exception translator.
 * 
 * @param sessionFactory
 *            the SessionFactory that this filter uses
 * @return the Session to use
 * @throws DataAccessResourceFailureException
 *             if the Session could not be created
 * @see org.springframework.orm.hibernate3.SessionFactoryUtils#getSession(SessionFactory,
 *      boolean)
 * @see org.hibernate.FlushMode#NEVER
 */
protected Session getSession(SessionFactory sessionFactory) throws DataAccessResourceFailureException {
    Session session = SessionFactoryUtils.getSession(sessionFactory, true);
    //TODO NEVER
    session.setFlushMode(FlushMode.AUTO);
    return session;
}

From source file:cz.zcu.kiv.eegdatabase.data.persistent.HibernateFilter.java

License:Apache License

@Override
protected Session getSession(SessionFactory sessionFactory) throws DataAccessResourceFailureException {
    Session session = SessionFactoryUtils.getSession(sessionFactory, true);

    // set FlushMode to AUTO in order to save objects.
    session.setFlushMode(FlushMode.AUTO);

    return session;
}