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.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  .  java2 s.  c  om*/
        }
        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.castafiore.persistence.DaoImpl.java

License:Open Source License

public Session getReadOnlySession() {
    try {//from  w w  w  .  j a va2 s  . c o  m
        Session session = SESSION_THREAD.get();
        if (session == null || !session.isOpen()) {
            session = getHibernateTemplate().getSessionFactory().openSession();
            session.setFlushMode(FlushMode.MANUAL);
            //session.setCacheMode(CacheMode.IGNORE);
            SESSION_THREAD.set(session);
        }
        return session;

    } catch (Exception e) {
        //return HibernateUtil.getSession(getHibernateTemplate().getSessionFactory());
        throw new RuntimeException(e);
    }
}

From source file:org.castafiore.persistence.DaoImpl.java

License:Open Source License

public Session getSession() {
    try {/*from ww  w  .  j a  v  a2s .  co  m*/
        Session session = SESSION_THREAD.get();
        if (session == null || !session.isOpen()) {
            session = getHibernateTemplate().getSessionFactory().openSession();
            session.setFlushMode(FlushMode.MANUAL);
            //session.setCacheMode(CacheMode.IGNORE);
            SESSION_THREAD.set(session);
        }

        Transaction t = TRANSACTION_THREAD.get();
        if (t == null) {
            t = session.beginTransaction();
            t.setTimeout(9000);
            TRANSACTION_THREAD.set(t);

        } else {
            if (!t.isActive()) {
                t.begin();
            }
        }
        return session;

    } catch (Exception e) {
        //return HibernateUtil.getSession(getHibernateTemplate().getSessionFactory());
        throw new RuntimeException(e);
    }
}

From source file:org.codehaus.grepo.query.hibernate.repository.DefaultHibernateRepository.java

License:Apache License

/**
 * Apply the flush mode that's been specified.
 *
 * @param sessionHolder The current session holder.
 * @param queryOptions the query options.
 *//*w w w  . j a  va 2 s. c  om*/
protected void applyFlushMode(CurrentSessionHolder sessionHolder, HibernateQueryOptions queryOptions) {
    HibernateFlushMode flushModeToUse = getFlushMode(queryOptions);

    if (flushModeToUse != null) {
        FlushMode flushModeToSet = null;
        FlushMode previousFlushMode = null;

        if (flushModeToUse == HibernateFlushMode.MANUAL) {
            if (sessionHolder.isExistingTransaction()) {
                previousFlushMode = sessionHolder.getSession().getFlushMode();
                if (!previousFlushMode.lessThan(FlushMode.COMMIT)) {
                    flushModeToSet = FlushMode.MANUAL;
                }
            } else {
                flushModeToSet = FlushMode.MANUAL;
            }
        } else if (flushModeToUse == HibernateFlushMode.EAGER) {
            if (sessionHolder.isExistingTransaction()) {
                previousFlushMode = sessionHolder.getSession().getFlushMode();
                if (!previousFlushMode.equals(FlushMode.AUTO)) {
                    flushModeToSet = FlushMode.AUTO;
                }
            }
            // else rely on default FlushMode.AUTO
        } else if (flushModeToUse == HibernateFlushMode.COMMIT) {
            if (sessionHolder.isExistingTransaction()) {
                previousFlushMode = sessionHolder.getSession().getFlushMode();
                if (previousFlushMode.equals(FlushMode.AUTO) || previousFlushMode.equals(FlushMode.ALWAYS)) {
                    flushModeToSet = FlushMode.COMMIT;
                }
            } else {
                flushModeToSet = FlushMode.COMMIT;
            }
        } else if (flushModeToUse == HibernateFlushMode.ALWAYS) {
            if (sessionHolder.isExistingTransaction()) {
                previousFlushMode = sessionHolder.getSession().getFlushMode();
                if (!previousFlushMode.equals(FlushMode.ALWAYS)) {
                    flushModeToSet = FlushMode.ALWAYS;
                }
            } else {
                flushModeToSet = FlushMode.ALWAYS;
            }
        }

        if (flushModeToSet != null) {
            logger.debug("Setting flushMode to '{}' for generic repository execution", flushModeToSet);
            sessionHolder.getSession().setFlushMode(flushModeToSet);
        }

        if (previousFlushMode != null) {
            sessionHolder.setPreviousFlushMode(previousFlushMode);
        }
    }
}

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

License:Apache License

/**
 * Sets the target object to read-only using the given SessionFactory instance. This
 * avoids Hibernate performing any dirty checking on the object
 *
 * @see #setObjectToReadWrite(Object, org.hibernate.SessionFactory)
 *
 * @param target The target object//from   w w  w . j  av a  2  s  . c  o m
 * @param sessionFactory The SessionFactory instance
 */
public static void setObjectToReadyOnly(Object target, SessionFactory sessionFactory) {
    Session session = sessionFactory.getCurrentSession();
    if (canModifyReadWriteState(session, target)) {
        if (target instanceof HibernateProxy) {
            target = ((HibernateProxy) target).getHibernateLazyInitializer().getImplementation();
        }
        session.setReadOnly(target, true);
        session.setFlushMode(FlushMode.MANUAL);
    }
}

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

License:Apache License

private Session createSession(Object resource) {
    LOG.debug("Opening Hibernate Session");

    SessionHolder sessionHolder = (SessionHolder) resource;

    Session session = sessionFactory.openSession();

    // Use same Session for further Hibernate actions within the transaction.
    // Thread object will get removed by synchronization at transaction completion.
    if (TransactionSynchronizationManager.isSynchronizationActive()) {
        // We're within a Spring-managed transaction, possibly from JtaTransactionManager.
        LOG.debug("Registering Spring transaction synchronization for new Hibernate Session");
        SessionHolder holderToUse = sessionHolder;
        if (holderToUse == null) {
            holderToUse = new SessionHolder(session);
        } else {//from   ww  w .  j  a v a  2  s  .  co m
            // it's up to the caller to manage concurrent sessions
            // holderToUse.addSession(session);
        }
        if (TransactionSynchronizationManager.isCurrentTransactionReadOnly()) {
            session.setFlushMode(FlushMode.MANUAL);
        }
        TransactionSynchronizationManager
                .registerSynchronization(createSpringSessionSynchronization(holderToUse));
        holderToUse.setSynchronizedWithTransaction(true);
        if (holderToUse != sessionHolder) {
            TransactionSynchronizationManager.bindResource(sessionFactory, holderToUse);
        }
    } else {
        // No Spring transaction management active -> try JTA transaction synchronization.
        registerJtaSynchronization(session, sessionHolder);
    }

    /*        // Check whether we are allowed to return the Session.
            if (!allowCreate && !isSessionTransactional(session, sessionFactory)) {
               closeSession(session);
               throw new IllegalStateException("No Hibernate Session bound to thread, " +
      "and configuration does not allow creation of non-transactional one here");
            }
    */
    return session;
}

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

License:Apache License

public void setFlushModeManual() {
    hibernateTemplate.execute(new HibernateCallback<Void>() {
        public Void doInHibernate(Session session) {
            session.setFlushMode(FlushMode.MANUAL);
            return null;
        }//from  w w w. ja  va  2  s  .c  o  m
    });
}

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.  ja va2s . com*/
        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();/* ww w.jav a 2  s.  co  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   w  w  w. j  ava2s  . com
    }
    super.closeSession(session, sessionFactory);
}