Example usage for org.hibernate Session getFlushMode

List of usage examples for org.hibernate Session getFlushMode

Introduction

In this page you can find the example usage for org.hibernate Session getFlushMode.

Prototype

@Override
FlushModeType getFlushMode();

Source Link

Document

For users of the Hibernate native APIs, we've had to rename this method as defined by Hibernate historically because the JPA contract defines a method of the same name, but returning the JPA FlushModeType rather than Hibernate's FlushMode .

Usage

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();//w  w  w.  ja va 2s.co  m
            } catch (HibernateException ex) {
                throw convertHibernateAccessException(ex);
            } finally {
                session.setFlushMode(FlushMode.MANUAL);
            }
        }
    }
}

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

License:Open Source License

/**
 * Retrieve the Spring-managed Session for the current thread, if any.
 *//*from   w  w w .  j  a v a2s. com*/
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();/*from   w  ww .  j  a v  a 2 s.  co m*/
            } 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.");
    }/*ww  w  .  j  ava  2 s  . c o  m*/

    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.broadleafcommerce.openadmin.server.service.persistence.module.BasicPersistenceModule.java

License:Apache License

@Override
public Serializable createPopulatedInstance(Serializable instance, Entity entity,
        Map<String, FieldMetadata> unfilteredProperties, Boolean setId, Boolean validateUnsubmittedProperties)
        throws ValidationException {
    final Map<String, FieldMetadata> mergedProperties = filterOutCollectionMetadata(unfilteredProperties);
    FieldManager fieldManager = getFieldManager();
    boolean handled = false;
    for (FieldPersistenceProvider fieldPersistenceProvider : fieldPersistenceProviders) {
        FieldProviderResponse response = fieldPersistenceProvider
                .filterProperties(new AddFilterPropertiesRequest(entity), unfilteredProperties);
        if (FieldProviderResponse.NOT_HANDLED != response) {
            handled = true;//from ww  w . ja v  a2  s. co m
        }
        if (FieldProviderResponse.HANDLED_BREAK == response) {
            break;
        }
    }
    if (!handled) {
        defaultFieldPersistenceProvider.filterProperties(new AddFilterPropertiesRequest(entity),
                unfilteredProperties);
    }
    //Order media field, map field and rule builder fields last, as they will have some validation components that depend on previous values
    Property[] sortedProperties = entity.getProperties();
    Arrays.sort(sortedProperties, new Comparator<Property>() {
        @Override
        public int compare(Property o1, Property o2) {
            BasicFieldMetadata mo1 = (BasicFieldMetadata) mergedProperties.get(o1.getName());
            BasicFieldMetadata mo2 = (BasicFieldMetadata) mergedProperties.get(o2.getName());
            boolean isLate1 = mo1 != null && mo1.getFieldType() != null && mo1.getName() != null
                    && (SupportedFieldType.RULE_SIMPLE == mo1.getFieldType()
                            || SupportedFieldType.RULE_WITH_QUANTITY == mo1.getFieldType()
                            || SupportedFieldType.MEDIA == mo1.getFieldType()
                            || o1.getName().contains(FieldManager.MAPFIELDSEPARATOR));
            boolean isLate2 = mo2 != null && mo2.getFieldType() != null && mo2.getName() != null
                    && (SupportedFieldType.RULE_SIMPLE == mo2.getFieldType()
                            || SupportedFieldType.RULE_WITH_QUANTITY == mo2.getFieldType()
                            || SupportedFieldType.MEDIA == mo2.getFieldType()
                            || o2.getName().contains(FieldManager.MAPFIELDSEPARATOR));
            if (isLate1 && !isLate2) {
                return 1;
            } else if (!isLate1 && isLate2) {
                return -1;
            }
            return 0;
        }
    });
    Session session = getPersistenceManager().getDynamicEntityDao().getStandardEntityManager()
            .unwrap(Session.class);
    FlushMode originalFlushMode = session.getFlushMode();
    try {
        session.setFlushMode(FlushMode.MANUAL);
        RuntimeException entityPersistenceException = null;
        for (Property property : sortedProperties) {
            BasicFieldMetadata metadata = (BasicFieldMetadata) mergedProperties.get(property.getName());
            Class<?> returnType;
            if (!property.getName().contains(FieldManager.MAPFIELDSEPARATOR)
                    && !property.getName().startsWith("__")) {
                Field field = fieldManager.getField(instance.getClass(), property.getName());
                if (field == null) {
                    LOG.debug("Unable to find a bean property for the reported property: " + property.getName()
                            + ". Ignoring property.");
                    continue;
                }
                returnType = field.getType();
            } else {
                if (metadata == null) {
                    LOG.debug("Unable to find a metadata property for the reported property: "
                            + property.getName() + ". Ignoring property.");
                    continue;
                }
                returnType = getMapFieldType(instance, fieldManager, property);
                if (returnType == null) {
                    returnType = getBasicBroadleafType(metadata.getFieldType());
                }
            }
            if (returnType == null) {
                throw new IllegalAccessException(
                        "Unable to determine the value type for the property (" + property.getName() + ")");
            }
            String value = property.getValue();
            if (metadata != null) {
                Boolean mutable = metadata.getMutable();
                Boolean readOnly = metadata.getReadOnly();

                if (metadata.getFieldType().equals(SupportedFieldType.BOOLEAN)) {
                    if (value == null) {
                        value = "false";
                    }
                }

                if ((mutable == null || mutable) && (readOnly == null || !readOnly)) {
                    if (value != null) {
                        handled = false;
                        PopulateValueRequest request = new PopulateValueRequest(setId, fieldManager, property,
                                metadata, returnType, value, persistenceManager, this);

                        boolean attemptToPopulate = true;
                        for (PopulateValueRequestValidator validator : populateValidators) {
                            PropertyValidationResult validationResult = validator.validate(request, instance);
                            if (!validationResult.isValid()) {
                                entity.addValidationError(property.getName(),
                                        validationResult.getErrorMessage());
                                attemptToPopulate = false;
                            }
                        }

                        if (attemptToPopulate) {
                            try {
                                boolean isBreakDetected = false;
                                for (FieldPersistenceProvider fieldPersistenceProvider : fieldPersistenceProviders) {
                                    if (!isBreakDetected || fieldPersistenceProvider.alwaysRun()) {
                                        FieldProviderResponse response = fieldPersistenceProvider
                                                .populateValue(request, instance);
                                        if (FieldProviderResponse.NOT_HANDLED != response) {
                                            handled = true;
                                        }
                                        if (FieldProviderResponse.HANDLED_BREAK == response) {
                                            isBreakDetected = true;
                                        }
                                    }
                                }
                                if (!handled) {
                                    defaultFieldPersistenceProvider.populateValue(
                                            new PopulateValueRequest(setId, fieldManager, property, metadata,
                                                    returnType, value, persistenceManager, this),
                                            instance);
                                }
                            } catch (ParentEntityPersistenceException
                                    | javax.validation.ValidationException e) {
                                entityPersistenceException = e;
                                cleanupFailedPersistenceAttempt(instance);
                                break;
                            }
                        }
                    } else {
                        try {
                            if (fieldManager.getFieldValue(instance, property.getName()) != null
                                    && (metadata.getFieldType() != SupportedFieldType.ID || setId)
                                    && metadata.getFieldType() != SupportedFieldType.PASSWORD) {
                                if (fieldManager.getFieldValue(instance, property.getName()) != null) {
                                    property.setIsDirty(true);
                                }
                                fieldManager.setFieldValue(instance, property.getName(), null);
                            }
                        } catch (FieldNotAvailableException e) {
                            throw new IllegalArgumentException(e);
                        }
                    }
                }
            }
        }
        validate(entity, instance, mergedProperties, validateUnsubmittedProperties);
        //if validation failed, refresh the current instance so that none of the changes will be persisted
        if (entity.isValidationFailure()) {
            //only refresh the instance if it was managed to begin with
            if (persistenceManager.getDynamicEntityDao().getStandardEntityManager().contains(instance)) {
                persistenceManager.getDynamicEntityDao().refresh(instance);
            }

            //re-initialize the valid properties for the entity in order to deal with the potential of not
            //completely sending over all checkbox/radio fields
            List<Serializable> entityList = new ArrayList<Serializable>(1);
            entityList.add(instance);
            Entity invalid = getRecords(mergedProperties, entityList, null, null)[0];
            invalid.setPropertyValidationErrors(entity.getPropertyValidationErrors());
            invalid.overridePropertyValues(entity);

            StringBuilder sb = new StringBuilder();
            for (Map.Entry<String, List<String>> entry : invalid.getPropertyValidationErrors().entrySet()) {
                Iterator<String> itr = entry.getValue().iterator();
                while (itr.hasNext()) {
                    sb.append(entry.getKey());
                    sb.append(" : ");
                    sb.append(itr.next());
                    if (itr.hasNext()) {
                        sb.append(" / ");
                    }
                }
            }

            throw new ValidationException(invalid, "The entity has failed validation - " + sb.toString());
        } else if (entityPersistenceException != null) {
            throw ExceptionHelper.refineException(entityPersistenceException.getCause());
        } else {
            fieldManager.persistMiddleEntities();
        }
    } catch (IllegalAccessException e) {
        throw new PersistenceException(e);
    } catch (InstantiationException e) {
        throw new PersistenceException(e);
    } finally {
        session.setFlushMode(originalFlushMode);
    }
    return instance;
}

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.
 *///www  .  j av a 2  s .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.codehaus.groovy.grails.orm.hibernate.support.ClosureEventListener.java

License:Apache License

private <T> T doWithManualSession(AbstractEvent event, Closure<T> callable) {
    Session session = event.getSession();
    FlushMode current = session.getFlushMode();
    try {//from w w  w  .j  av a2s .co  m
        session.setFlushMode(FlushMode.MANUAL);
        return callable.call();
    } finally {
        session.setFlushMode(current);
    }
}

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

License:Apache License

public void responseRedirected(String url) {
    new HibernateTemplate(sessionFactory).execute(new HibernateCallback<Void>() {
        public Void doInHibernate(Session session) {
            if (session.getFlushMode() != FlushMode.MANUAL) {
                session.flush();//from w  ww . jav  a2 s .c  o m
            }
            return null;
        }
    });
}

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

License:Apache License

@Override
protected void closeSession(Session session, SessionFactory sessionFactory) {
    if (!FlushMode.MANUAL.equals(session.getFlushMode())) {
        session.flush();//from  ww w. j a  v  a  2  s.  co  m
    }
    super.closeSession(session, sessionFactory);
}

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

License:Apache License

@Override
protected void flushIfNecessary(Session session, boolean existingTransaction) throws HibernateException {
    if (session != null && session.getFlushMode() != FlushMode.MANUAL) {
        super.flushIfNecessary(session, existingTransaction);
    }//from w  ww .ja  v  a  2 s.co m
}