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:org.babyfish.hibernate.model.loader.HibernateObjectModelScalarLoader.java

License:Open Source License

@SuppressWarnings("unchecked")
private void loadScalarsImpl(Collection<ObjectModel> objectModels, int[] scalarPropertyIds) {
    boolean batch = objectModels.size() > 1;
    ObjectModel firstObjectModel = objectModels.iterator().next();
    JPAObjectModelMetadata jpaObjectModelMetadata = (JPAObjectModelMetadata) firstObjectModel
            .getObjectModelMetadata();//  w ww  . j  a v  a 2 s .c o  m
    JPAScalarProperty entityIdProperty = jpaObjectModelMetadata.getEntityIdProperty();
    Map<Object, ObjectModel> idMap = new LinkedHashMap<>();
    for (ObjectModel objectModel : objectModels) {
        idMap.put(objectModel.getScalar(entityIdProperty.getId()), objectModel);
    }

    CriteriaImpl criteria = new CriteriaImpl(jpaObjectModelMetadata.getOwnerClass().getName(), session);
    ProjectionList projectionList = Projections.projectionList();
    if (batch) {
        String ownerIdPropertyName = entityIdProperty.getOwnerProperty().getName();
        projectionList.add(Projections.property(ownerIdPropertyName));
    }
    for (int scalarPropertyId : scalarPropertyIds) {
        String ownerPropertyName = jpaObjectModelMetadata.getScalarProperty(scalarPropertyId).getOwnerProperty()
                .getName();
        projectionList.add(Projections.property(ownerPropertyName));
    }
    if (batch) {
        criteria.add(Restrictions.in(entityIdProperty.getOwnerProperty().getName(), idMap.keySet()));
    } else {
        criteria.add(Restrictions.eq(entityIdProperty.getOwnerProperty().getName(),
                idMap.keySet().iterator().next()));
    }
    criteria.setProjection(projectionList).setResultTransformer(new ResultTransformer() {

        private static final long serialVersionUID = -1387181124646452221L;

        @Override
        public Object transformTuple(Object[] tuple, String[] aliases) {
            return tuple;
        }

        @SuppressWarnings("rawtypes")
        @Override
        public List transformList(List collection) {
            return collection;
        }
    });
    List<Object[]> tuples;
    FlushMode oldFlushMode = session.getFlushMode();
    session.setFlushMode(FlushMode.MANUAL);
    try {
        tuples = (List<Object[]>) criteria.list();
    } finally {
        session.setFlushMode(oldFlushMode);
    }
    if (batch) {
        for (Object[] tuple : tuples) {
            ObjectModel objectModel = idMap.get(tuple[0]);
            for (int i = scalarPropertyIds.length - 1; i >= 0; i--) {
                objectModel.setScalar(scalarPropertyIds[i], tuple[i + 1]);
            }
        }
    } else {
        Object[] firstTuple = tuples.get(0);
        for (int i = scalarPropertyIds.length - 1; i >= 0; i--) {
            firstObjectModel.setScalar(scalarPropertyIds[i], firstTuple[i]);
        }
    }
}

From source file:org.beangle.commons.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.");
    }//www.j  a va 2 s  . c  om

    Session session = null;

    try {
        if (txObject.getSessionHolder() == null
                || txObject.getSessionHolder().isSynchronizedWithTransaction()) {
            Interceptor entityInterceptor = getEntityInterceptor();
            Session newSession = (entityInterceptor != null ? getSessionFactory().openSession(entityInterceptor)
                    : getSessionFactory().openSession());
            if (logger.isDebugEnabled()) {
                logger.debug("Opened new Session [" + SessionUtils.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 [" + SessionUtils.toString(session)
                        + "]");
            }
            @SuppressWarnings("deprecation")
            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' (BeangleTransactionFactory's default). "
                                + "Make sure that your SessionFactoryBean actually uses BeangleTransactionFactory: Your "
                                + "Hibernate properties should *not* include a 'hibernate.transaction.factory_class' property!");
            }
            if (logger.isDebugEnabled()) {
                logger.debug("Not preparing JDBC Connection of Hibernate Session ["
                        + SessionUtils.toString(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.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) {
            @SuppressWarnings("deprecation")
            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 (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.beangle.commons.orm.hibernate.HibernateTransactionManager.java

License:Open Source License

@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();//from   w w  w . j a v  a2s  .  c  o  m
            } catch (HibernateException ex) {
                throw convertHibernateAccessException(ex);
            } finally {
                session.setFlushMode(FlushMode.MANUAL);
            }
        }
    }
}

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  va 2s .  c om*/

    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.beangle.orm.hibernate.internal.SessionUtils.java

License:Open Source License

public static SessionHolder openSession(SessionFactory factory)
        throws DataAccessResourceFailureException, IllegalStateException {
    try {/*from  w w w .j  a  v a2s.  c o m*/
        SessionHolder holder = (SessionHolder) getResource(factory);
        Session session = null;
        if (null == holder) {
            session = factory.openSession();
            session.setFlushMode(FlushMode.MANUAL);
            holder = new SessionHolder(session);
            if (isEnableBinding(factory))
                bindResource(factory, holder);
        }
        return holder;
    } catch (HibernateException ex) {
        throw new DataAccessResourceFailureException("Could not open Hibernate Session", ex);
    }
}

From source file:org.bedework.calcore.hibernate.CalintfImpl.java

License:Apache License

@Override
public synchronized void open(final boolean webMode, final boolean forRestore, final boolean indexRebuild)
        throws CalFacadeException {
    if (isOpen) {
        throw new CalFacadeException("Already open");
    }//w  ww  .j  a v a  2s . c  o m

    isOpen = true;
    this.forRestore = forRestore;
    this.indexRebuild = indexRebuild;

    if ((sess != null) && !webMode) {
        warn("Session is not null. Will close");
        try {
            close();
        } finally {
        }
    }

    if (sess == null) {
        if (debug) {
            debug("New hibernate session for " + getTraceId());
        }
        sess = new HibSessionImpl();
        sess.init(getSessionFactory(), getLogger());
        if (webMode) {
            sess.setFlushMode(FlushMode.MANUAL);
        } else if (debug) {
            debug("Open session for " + getTraceId());
        }
    }

    if (access != null) {
        access.open();
    }
}

From source file:org.bedework.dumprestore.restore.HibRestore.java

@Override
public void restoreEvent(final EventInfo ei) throws Throwable {
    try {/*from  w w w .j  av a  2  s  . c o m*/
        BwEvent ev = ei.getEvent();
        BwEvent saveEv = ev;

        if (!globals.onlyUsersMap.check(ev)) {
            return;
        }
        globals.currentUser = (BwUser) globals.getPrincipal(ev.getOwnerHref());

        if (ev instanceof BwEventProxy) {
            BwEventProxy proxy = (BwEventProxy) ev;
            saveEv = proxy.getRef();
        }

        openHibSess(FlushMode.MANUAL);
        CoreEventsI evi = getEvents((BwUser) globals.getPrincipal(ev.getCreatorHref()));
        UpdateEventResult uer = evi.addEvent(saveEv, ei.getOverrideProxies(), false, // scheduling
                false);

        if (!uer.addedUpdated) {
            throw new CalFacadeException(uer.errorCode);
        }
        if (uer.failedOverrides != null) {
            error("Following overrides failed for event ");
            error(ev.toString());

            for (BwEventProxy proxy : uer.failedOverrides) {
                error(proxy.toString());
            }
        }
    } finally {
        closeHibSess();
    }
}

From source file:org.bedework.dumprestore.restore.HibRestore.java

@Override
public BwEvent getEvent(final BwUser user, final String colPath, final String recurrenceId, final String uid)
        throws Throwable {
    /* Open the session if not already open. Note we don't close it - that will
     * happen later./*from   w  w  w.  java2s. c  o  m*/
     */
    openHibSess(FlushMode.MANUAL);
    CoreEventsI evi = getEvents(user);

    Collection<CoreEventInfo> ceis = evi.getEvent(colPath, uid, recurrenceId, false,
            new RecurringRetrievalMode(Rmode.entityOnly));
    /*
    Query q = hibSess.createQuery("from " + BwEventObj.class.getName() +
                             " ev where ev.calendar=:cal " +
                             " and ev.uid=:uid ");
    q.setEntity("cal", cal);
    q.setString("uid", guid);
    BwEvent ev = (BwEvent)q.uniqueResult();
    */

    if (ceis.size() != 1) {
        error("Expected one event for {" + colPath + ", " + recurrenceId + ", " + uid + "} found "
                + ceis.size());
        return null;
    }

    BwEvent ev = ceis.iterator().next().getEvent();

    if (ev instanceof BwEventAnnotation) {
        ev = new BwEventProxy((BwEventAnnotation) ev);
    }

    return ev;
}

From source file:org.bedework.dumprestore.restore.HibRestore.java

private synchronized void openHibSess(final FlushMode fm) throws Throwable {
    if (hibSess == null) {
        hibSession = new HibSessionImpl();
        hibSession.init(sessFactory, Logger.getLogger(getClass()));

        hibSess = hibSession.getSession();
        hibSess.setFlushMode(fm);//from  w  w  w. ja  v  a2  s .  c  o m
        hibSess.beginTransaction();
        manualFlush = fm.equals(FlushMode.MANUAL);
    }
}

From source file:org.broadleafcommerce.common.dao.GenericEntityDaoImpl.java

License:Apache License

@Override
public void clearAutoFlushMode() {
    em.unwrap(Session.class).setFlushMode(FlushMode.MANUAL);
}