Example usage for org.hibernate Session setFlushMode

List of usage examples for org.hibernate Session setFlushMode

Introduction

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

Prototype

@Deprecated
void setFlushMode(FlushMode flushMode);

Source Link

Document

Set the flush mode for this session.

Usage

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

License:Apache License

@Override
public void postHandle(WebRequest request, ModelMap model) throws DataAccessException {
    final boolean isFlowRequest = request.getAttribute(IS_FLOW_REQUEST_ATTRIBUTE,
            WebRequest.SCOPE_REQUEST) != null;
    if (isFlowRequest) {
        return;//from www . j a  v a 2 s  . c  o  m
    }

    try {
        super.postHandle(request, model);
    } finally {
        SessionHolder sessionHolder = (SessionHolder) TransactionSynchronizationManager
                .getResource(getSessionFactory());
        Session session = sessionHolder.getSession();
        session.setFlushMode(FlushMode.MANUAL);
    }
}

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

License:Apache License

public void init() {
    if (incNestingCount() > 1) {
        return;/* ww w . j a v a  2  s .c o m*/
    }
    SessionFactory sf = getSessionFactory();
    if (TransactionSynchronizationManager.hasResource(sf)) {
        // Do not modify the Session: just set the participate flag.
        setParticipate(true);
    } else {
        setParticipate(false);
        LOG.debug("Opening single Hibernate session in HibernatePersistenceContextInterceptor");
        Session session = getSession();
        GrailsHibernateUtil.enableDynamicFilterEnablerIfPresent(sf, session);
        session.setFlushMode(FlushMode.AUTO);
        TransactionSynchronizationManager.bindResource(sf, new SessionHolder(session));
    }
}

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

License:Apache License

@Override
protected void processValidate(final Object target, final Object propertyValue, Errors errors) {
    if (!unique) {
        return;/*from   w ww .  jav  a2s  . c o  m*/
    }

    final Object id;
    try {
        id = InvokerHelper.invokeMethod(target, "ident", null);
    } catch (Exception e) {
        throw new GrailsRuntimeException("Target of [unique] constraints [" + target
                + "] is not a domain instance. Unique constraint can only be applied to to domain classes and not custom user types or embedded instances");
    }

    HibernateTemplate hibernateTemplate = getHibernateTemplate();
    if (hibernateTemplate == null)
        throw new IllegalStateException("Unable use [unique] constraint, no Hibernate SessionFactory found!");
    List<?> results = hibernateTemplate.executeFind(new HibernateCallback<List<?>>() {
        public List<?> doInHibernate(Session session) throws HibernateException {
            session.setFlushMode(FlushMode.MANUAL);
            try {
                boolean shouldValidate = true;
                Class<?> constraintClass = constraintOwningClass;
                if (propertyValue != null
                        && DomainClassArtefactHandler.isDomainClass(propertyValue.getClass())) {
                    shouldValidate = session.contains(propertyValue);
                }
                if (shouldValidate) {
                    GrailsApplication application = (GrailsApplication) applicationContext
                            .getBean(GrailsApplication.APPLICATION_ID);
                    GrailsDomainClass domainClass = (GrailsDomainClass) application
                            .getArtefact(DomainClassArtefactHandler.TYPE, constraintClass.getName());
                    if (domainClass != null && !domainClass.isRoot()) {
                        GrailsDomainClassProperty property = domainClass
                                .getPropertyByName(constraintPropertyName);
                        while (property.isInherited() && domainClass != null) {
                            domainClass = (GrailsDomainClass) application.getArtefact(
                                    DomainClassArtefactHandler.TYPE,
                                    domainClass.getClazz().getSuperclass().getName());
                            if (domainClass != null) {
                                property = domainClass.getPropertyByName(constraintPropertyName);
                            }
                        }
                        constraintClass = domainClass != null ? domainClass.getClazz() : constraintClass;
                    }
                    Criteria criteria = session.createCriteria(constraintClass)
                            .add(Restrictions.eq(constraintPropertyName, propertyValue));
                    if (uniquenessGroup != null) {
                        for (Object anUniquenessGroup : uniquenessGroup) {
                            String uniquenessGroupPropertyName = (String) anUniquenessGroup;
                            Object uniquenessGroupPropertyValue = GrailsClassUtils
                                    .getPropertyOrStaticPropertyOrFieldValue(target,
                                            uniquenessGroupPropertyName);

                            if (uniquenessGroupPropertyValue != null && DomainClassArtefactHandler
                                    .isDomainClass(uniquenessGroupPropertyValue.getClass())) {
                                try {
                                    // We are merely verifying that the object is not transient here
                                    session.lock(uniquenessGroupPropertyValue, LockMode.NONE);
                                } catch (TransientObjectException e) {
                                    shouldValidate = false;
                                }
                            }
                            if (shouldValidate) {
                                criteria.add(Restrictions.eq(uniquenessGroupPropertyName,
                                        uniquenessGroupPropertyValue));
                            } else {
                                break; // we aren't validating, so no point continuing
                            }
                        }
                    }

                    if (shouldValidate) {
                        return criteria.list();
                    }
                    return Collections.EMPTY_LIST;
                }
                return Collections.EMPTY_LIST;
            } finally {
                session.setFlushMode(FlushMode.AUTO);
            }
        }
    });

    if (results.isEmpty()) {
        return;
    }

    boolean reject = false;
    if (id != null) {
        Object existing = results.get(0);
        Object existingId = null;
        try {
            existingId = InvokerHelper.invokeMethod(existing, "ident", null);
        } catch (Exception e) {
            // result is not a domain class
        }
        if (!id.equals(existingId)) {
            reject = true;
        }
    } else {
        reject = true;
    }
    if (reject) {
        Object[] args = new Object[] { constraintPropertyName, constraintOwningClass, propertyValue };
        rejectValue(target, errors, UNIQUE_CONSTRAINT, args,
                getDefaultMessage(DEFAULT_NOT_UNIQUE_MESSAGE_CODE));
    }
}

From source file:org.eclipse.emf.teneo.hibernate.resource.HbResourceImpl.java

License:Open Source License

/**
 * Creates the session of this resource. As a default the FlushMode is set
 * to Never. The loaded objects of this resource are merged into the
 * session. It is the responsibility of the caller to close the session or
 * call the returnSession method here./*from w  w  w  .ja  v  a  2 s. c o  m*/
 */
public Session getSession() {
    if (log.isDebugEnabled()) {
        log.debug("Creating session");
    }
    final SessionFactory sessionFactory = emfDataStore.getSessionFactory();
    final Session session = sessionFactory.openSession();
    session.setFlushMode(FlushMode.MANUAL);

    if (loadedEObjects.size() > 0) {
        session.beginTransaction();

        // merge the loaded objects into the session
        if (log.isDebugEnabled()) {
            log.debug("Merging " + loadedEObjects.size() + " eobjects into new session ");
        }
        for (Object obj : loadedEObjects) {
            session.buildLockRequest(LockOptions.NONE).lock(obj);
        }
        session.getTransaction().commit();
    }

    return session;
}

From source file:org.ednovo.gooru.web.listener.StartupListener.java

License:Open Source License

/**
 * Gets a Session for the SessionFactory that this listener uses. Note that
 * this just applies in single session mode!
 * <p>/*from   w w w .j  a  v a 2 s.  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 listener uses
 * @return the Session to use
 * @throws org.springframework.dao.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 = sessionFactory.openSession();
    session.setFlushMode(FlushMode.MANUAL);
    return session;
}

From source file:org.encuestame.persistence.filter.SessionFilter.java

License:Apache License

protected Session getSession(SessionFactory sessionFactory) throws DataAccessResourceFailureException {
    Session session = super.getSession(sessionFactory);
    session.setFlushMode(FlushMode.AUTO);
    return session;
}

From source file:org.fornax.cartridges.sculptor.framework.web.hibernate.OpenHibernateSessionInConversationListener.java

License:Apache License

private Session createSession(RequestContext context) {
    Session session = (entityInterceptor != null ? sessionFactory.openSession(entityInterceptor)
            : sessionFactory.openSession());
    session.setFlushMode(FlushMode.MANUAL);
    return session;
}

From source file:org.forzaframework.orm.hibernate3.support.OpenSessionInThreadTask.java

License:Apache License

protected Session getSession(SessionFactory sessionFactory) throws DataAccessResourceFailureException {
    Session session = SessionFactoryUtils.getSession(sessionFactory, true);
    FlushMode flushMode = FlushMode.MANUAL;
    if (flushMode != null) {
        session.setFlushMode(flushMode);
    }/*from ww w .j  a  v a 2s  . c om*/
    return session;
}

From source file:org.generationcp.middleware.operation.saver.WorkbookSaver.java

License:Open Source License

public void createStocksIfNecessary(final int datasetId, final Workbook workbook,
        final VariableTypeList effectVariables, final List<String> trialHeaders) {
    final Map<String, Integer> stockMap = this.getStockModelBuilder().getStockMapForDataset(datasetId);

    List<Integer> variableIndexesList = new ArrayList<>();
    // we get the indexes so that in the next rows we dont need to compare
    // anymore per row
    if (workbook.getObservations() != null && !workbook.getObservations().isEmpty()) {
        final MeasurementRow row = workbook.getObservations().get(0);
        variableIndexesList = this.getVariableListTransformer().transformStockIndexes(row, effectVariables,
                trialHeaders);// ww  w.j a va  2s.  c om
    }

    if (workbook.getObservations() != null) {
        final Session activeSession = this.getActiveSession();
        final FlushMode existingFlushMode = activeSession.getFlushMode();
        activeSession.setFlushMode(FlushMode.MANUAL);
        try {
            for (final MeasurementRow row : workbook.getObservations()) {

                final VariableList stock = this.getVariableListTransformer()
                        .transformStockOptimize(variableIndexesList, row, effectVariables, trialHeaders);
                final String stockFactor = this.getStockFactor(stock);
                Integer stockId = stockMap.get(stockFactor);

                if (stockId == null) {
                    stockId = this.getStockSaver().saveStock(stock);
                    stockMap.put(stockFactor, stockId);
                } else {
                    this.getStockSaver().saveOrUpdateStock(stock, stockId);
                }
                row.setStockId(stockId);
            }
            activeSession.flush();
        } finally {
            if (existingFlushMode != null) {
                activeSession.setFlushMode(existingFlushMode);
            }
        }
    }

}

From source file:org.generationcp.middleware.operation.saver.WorkbookSaver.java

License:Open Source License

private void createMeasurementEffectExperiments(final CropType crop, final int datasetId,
        final VariableTypeList effectVariables, final List<MeasurementRow> observations,
        final List<String> trialHeaders) {

    final TimerWatch watch = new TimerWatch("saving stocks and measurement effect data (total)");
    final TimerWatch rowWatch = new TimerWatch("for each row");

    // observation values start at row 2
    int i = 2;//from   w  w  w.jav  a  2 s  .  co  m

    final ExperimentValuesTransformer experimentValuesTransformer = this.getExperimentValuesTransformer();
    final ExperimentModelSaver experimentModelSaver = this.getExperimentModelSaver();
    Map<Integer, PhenotypeExceptionDto> exceptions = null;
    final Session activeSession = this.getActiveSession();
    final FlushMode existingFlushMode = activeSession.getFlushMode();
    try {
        activeSession.setFlushMode(FlushMode.MANUAL);
        if (observations != null) {
            for (final MeasurementRow row : observations) {
                rowWatch.restart("saving row " + i++);
                final ExperimentValues experimentValues = experimentValuesTransformer.transform(row,
                        effectVariables, trialHeaders);
                try {
                    experimentModelSaver.addExperiment(crop, datasetId, ExperimentType.PLOT, experimentValues);
                } catch (final PhenotypeException e) {
                    WorkbookSaver.LOG.error(e.getMessage(), e);
                    if (exceptions == null) {
                        exceptions = e.getExceptions();
                    } else {
                        for (final Integer standardVariableId : e.getExceptions().keySet()) {
                            final PhenotypeExceptionDto exception = e.getExceptions().get(standardVariableId);
                            if (exceptions.get(standardVariableId) == null) {
                                // add exception
                                exceptions.put(standardVariableId, exception);
                            } else {
                                // add invalid values to the existing map of
                                // exceptions for each phenotype
                                for (final String invalidValue : exception.getInvalidValues()) {
                                    exceptions.get(standardVariableId).getInvalidValues().add(invalidValue);
                                }
                            }
                        }
                    }
                }
            }
        }
        activeSession.flush();
    } finally {
        if (existingFlushMode != null) {
            activeSession.setFlushMode(existingFlushMode);
        }
    }

    rowWatch.stop();
    watch.stop();

    if (exceptions != null) {
        throw new PhenotypeException(exceptions);
    }
}