Example usage for org.hibernate FlushMode MANUAL

List of usage examples for org.hibernate FlushMode MANUAL

Introduction

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

Prototype

FlushMode MANUAL

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

Click Source Link

Document

The Session is only ever flushed when Session#flush is explicitly called by the application.

Usage

From source file:com.abiquo.abiserver.persistence.hibernate.HibernateUtil.java

License:Open Source License

public static Session getSession(final boolean ro) {
    if (ro) {/*  w  w  w  .  j av  a2s .c  o m*/
        sessionFactory.getCurrentSession().setFlushMode(FlushMode.MANUAL);
    } else {
        sessionFactory.getCurrentSession().setFlushMode(FlushMode.AUTO);
    }
    return sessionFactory.getCurrentSession();
}

From source file:com.amalto.core.storage.hibernate.HibernateStorage.java

License:Open Source License

@Override
public synchronized StorageTransaction newStorageTransaction() {
    assertPrepared();//from  w ww . j a  v a2s . c  o  m
    Session session = factory.openSession();
    session.setFlushMode(FlushMode.MANUAL);
    return new HibernateStorageTransaction(this, session);
}

From source file:com.bloatit.data.DataManager.java

License:Open Source License

/**
 * Set the current transaction read only.
 * //from w  w  w.  j  a  v  a  2 s.co m
 * @see DataManager#open()
 * @see DataManager#close()
 */
public static void setReadOnly() {
    final Session session = SessionManager.getSessionFactory().getCurrentSession();
    session.setDefaultReadOnly(true);
    session.setFlushMode(FlushMode.MANUAL);
}

From source file:com.bluexml.side.Framework.alfresco.jbpm.CustomJBPMEngine.java

License:Open Source License

@SuppressWarnings({ "unchecked", "cast" })
private void cacheVariablesNoBatch(Session session, List<Long> contextInstanceIds,
        Map<Long, TokenVariableMap> variablesCache) {
    Query query = session.getNamedQuery("org.alfresco.repo.workflow.cacheInstanceVariables");
    query.setParameterList("ids", contextInstanceIds);
    query.setCacheMode(CacheMode.PUT);//w w w .  ja v  a 2 s .co  m
    query.setFlushMode(FlushMode.MANUAL);
    query.setCacheable(true);

    List<TokenVariableMap> results = (List<TokenVariableMap>) query.list();
    for (TokenVariableMap tokenVariableMap : results) {
        variablesCache.put(tokenVariableMap.getContextInstance().getId(), tokenVariableMap);
    }
}

From source file:com.bluexml.side.Framework.alfresco.jbpm.CustomJBPMEngine.java

License:Open Source License

@SuppressWarnings({ "unchecked", "cast" })
private void cacheTasksNoBatch(Session session, List<Long> taskInstanceIds, Map<Long, TaskInstance> returnMap) {
    Query query = session.getNamedQuery("org.alfresco.repo.workflow.cacheTaskInstanceProperties");
    query.setParameterList("ids", taskInstanceIds);
    query.setCacheMode(CacheMode.PUT);/*  w w w . j  av a  2  s  .c  om*/
    query.setFlushMode(FlushMode.MANUAL);
    query.setCacheable(true);

    List<TaskInstance> results = (List<TaskInstance>) query.list();
    for (TaskInstance taskInstance : results) {
        returnMap.put(taskInstance.getId(), taskInstance);
    }
}

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.");
    }//w w w  . j a va 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.celements.payment.service.PayPalService.java

License:Open Source License

public PayPal loadPayPalObject(final String txnId) throws XWikiException {
    boolean bTransaction = true;

    PayPal payPalObj = new PayPal();
    payPalObj.setTxn_id(txnId);// ww  w .jav  a2s.c o m

    getStore().checkHibernate(getContext());

    SessionFactory sfactory = getStore().injectCustomMappingsInSessionFactory(getContext());
    bTransaction = bTransaction && getStore().beginTransaction(sfactory, false, getContext());
    Session session = getStore().getSession(getContext());
    session.setFlushMode(FlushMode.MANUAL);

    try {
        session.load(payPalObj, payPalObj.getTxn_id());
    } catch (ObjectNotFoundException exp) {
        LOGGER.debug("no paypal object for txn_id [" + payPalObj.getTxn_id() + "] in" + " database ["
                + getContext().getDatabase() + "] found.");
        // No paypall object in store
    }
    LOGGER.trace("successfully loaded paypal object for txn_id [" + payPalObj.getTxn_id() + "] in database ["
            + getContext().getDatabase() + "] :" + payPalObj.getOrigMessage());
    return payPalObj;
}

From source file:com.celements.payment.service.PostFinanceService.java

License:Open Source License

public PostFinance loadPostFinanceObject(final String txnId) throws XWikiException {
    boolean bTransaction = true;

    PostFinance postFinanceObj = new PostFinance();
    postFinanceObj.setTxn_id(txnId);/*w  w  w .ja  va2 s .c om*/

    getStore().checkHibernate(getContext());

    SessionFactory sfactory = getStore().injectCustomMappingsInSessionFactory(getContext());
    bTransaction = bTransaction && getStore().beginTransaction(sfactory, false, getContext());
    Session session = getStore().getSession(getContext());
    session.setFlushMode(FlushMode.MANUAL);

    try {
        session.load(postFinanceObj, postFinanceObj.getTxn_id());
    } catch (ObjectNotFoundException exp) {
        LOGGER.debug("no PostFinance object for txn_id [" + postFinanceObj.getTxn_id() + "] in" + " database ["
                + getContext().getDatabase() + "] found.");
        // No PostFinancel object in store
    }
    LOGGER.trace("successfully loaded PostFinance object for txn_id [" + postFinanceObj.getTxn_id()
            + "] in database [" + getContext().getDatabase() + "] :" + postFinanceObj.getOrigMessage());
    return postFinanceObj;
}

From source file:com.creative.dao.repository.GenericBatchDaoImpl.java

License:Apache License

@Override
public int executeUpdate(Query query) {
    Session session = sessionFactory.getCurrentSession();
    session.setCacheMode(CacheMode.IGNORE);
    session.setFlushMode(FlushMode.MANUAL);
    int rows = query.executeUpdate();
    session.flush();/* w ww.j a v a2s .  c o  m*/

    logger.info("Updated rows  " + rows + " for " + query.getQueryString());
    return rows;
}

From source file:com.creative.dao.repository.GenericBatchDaoImpl.java

License:Apache License

private <T> int executeBatch(BatchType batchType, List<T> list) {
    Session session = sessionFactory.getCurrentSession();
    session.setCacheMode(CacheMode.IGNORE);
    session.setFlushMode(FlushMode.MANUAL);
    logger.info("Executing  Batch of size :" + list.size() + " given batch size is:" + batchSize);

    for (int i = 0; i < list.size(); i++) {
        switch (batchType) {
        case BATCH_INSERT:
            session.save(list.get(i));//from  w  ww  .j a v a2  s.c o  m
            break;
        case BATCH_DELETE:
            session.delete(list.get(i));
            break;
        case BATCH_INSERT_OR_UPDATE:
            session.saveOrUpdate(list.get(i));
        default:
            // nothing;
        }
        if (i > 0 && i % batchSize == 0) {
            logger.info("Flushing and clearing the cache" + " after row number :" + i);
            session.flush();
            session.clear();
        }

    }
    session.flush();
    return list.size();
}