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.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   w  w  w  . ja v a2  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.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  .jav  a  2  s  .  c  o m
}

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

License:Apache License

public void setReadOnly() {
    getSession().setFlushMode(FlushMode.MANUAL);
}

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

License:Apache License

@Override
public void validate(Object obj, Errors errors, boolean cascade) {
    final Session session = sessionFactory.getCurrentSession();
    FlushMode previousMode = null;/*w  w w. j av  a 2 s . co m*/
    try {
        if (session != null) {
            previousMode = session.getFlushMode();
            session.setFlushMode(FlushMode.MANUAL);
        }

        super.validate(obj, errors, cascade);
    } finally {
        if (session != null && previousMode != null && !errors.hasErrors()) {
            session.setFlushMode(previousMode);
        }
    }
}

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   www .  j  ava2s  . 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.codehaus.groovy.grails.plugins.quartz.listeners.SessionBinderJobListener.java

License:Apache License

public void jobWasExecuted(JobExecutionContext context, JobExecutionException exception) {
    SessionHolder sessionHolder = (SessionHolder) TransactionSynchronizationManager
            .unbindResource(sessionFactory);
    if (!FlushMode.MANUAL.equals(sessionHolder.getSession().getFlushMode())) {
        sessionHolder.getSession().flush();
    }/*from   w  ww.ja va2 s .co  m*/
    SessionFactoryUtils.closeSession(sessionHolder.getSession());
    if (LOG.isDebugEnabled())
        LOG.debug("Hibernate Session is unbounded from Job thread and closed");
}

From source file:org.compass.gps.device.hibernate.HibernateSyncTransaction.java

License:Apache License

public void begin(InternalCompassSession session) throws CompassException {
    this.session = session;
    try {//  ww  w.ja va 2  s  . c o  m
        controllingNewTransaction = true;
        SessionImplementor hibernateSession = ((SessionImplementor) sessionFactory.getCurrentSession());
        newTransaction = !hibernateSession.isTransactionInProgress();
        transaction = sessionFactory.getCurrentSession().getTransaction();
        if (newTransaction) {
            if (log.isDebugEnabled()) {
                log.debug("Beginning new Hibernate transaction, and a new compass transaction on thread ["
                        + Thread.currentThread().getName() + "]");
            }
            session.getSearchEngine().begin();
            if (session.isReadOnly()) {
                hibernateSession.setFlushMode(FlushMode.MANUAL);
            }
            transaction.begin();
        } else {
            // joining an exisiting transaction
            session.getSearchEngine().begin();
            if (log.isDebugEnabled()) {
                log.debug(
                        "Joining an existing Hibernate transaction, starting a new compass transaction on thread ["
                                + Thread.currentThread().getName() + "]");
            }
        }
        transaction.registerSynchronization(new HibernateTransactionSynchronization(session, transaction,
                newTransaction, commitBeforeCompletion, transactionFactory));
    } catch (Exception e) {
        throw new TransactionException("Begin failed with exception", e);
    }
    setBegun(true);
}

From source file:org.eclipse.emf.cdo.server.internal.hibernate.HibernateStoreAccessor.java

License:Open Source License

/**
 * Starts a hibernate session and begins a transaction.
 *
 * @since 2.0//from  w  w w  . j  ava2  s  .c o m
 */
public void beginHibernateSession() {
    if (TRACER.isEnabled()) {
        TRACER.trace("Creating hibernate session and transaction"); //$NON-NLS-1$
    }

    assert hibernateSession == null;
    final SessionFactory sessionFactory = getStore().getHibernateSessionFactory();
    hibernateSession = sessionFactory.openSession();
    hibernateSession.setDefaultReadOnly(true);
    hibernateSession.setFlushMode(FlushMode.MANUAL);
    hibernateSession.beginTransaction();
}

From source file:org.eclipse.emf.teneo.hibernate.HbSessionWrapper.java

License:Open Source License

/** Set the flushmode */
public void setFlushModeManual() {
    flushMode = getSessionInternal().getFlushMode();
    getSessionInternal().setFlushMode(FlushMode.MANUAL);
}

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 ww .j  a  v a2  s . c  om*/
 */
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;
}