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.dafoe.framework.samples.hibernate.OntologicalSamples.java

License:Open Source License

/**
 * Gets the all class sample.//  w  ww .  j a  va 2 s.c o  m
 * 
 * @return the all class sample
 */
@SuppressWarnings("unchecked")
public static List<IClass> getAllClassSample() throws HibernateException {//ok
    Session hSession = getDafoeSession();

    List<IClass> classes = hSession.createCriteria(ClassImpl.class).list();
    System.out.println(hSession.getFlushMode().toString());
    System.out.println("size= " + classes.size());

    for (IClass cls : classes) {
        // IDocument doc=s.getDocument();
        System.out.println("class id= " + cls.getId() + " || label= " + "|| child size= "
                + cls.getChildren().size() + "|| parent size= " + cls.getParents().size() + "|| dataprop size= "
                + cls.getDatatypeProperties().size() + " objectprop size=" + cls.getObjectProperties().size());
    }

    return classes;

}

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);//from   w  w  w  .  j a v  a  2 s .  co  m
    }

    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.  ja v a2 s  .  com*/

    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);
    }
}

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

License:Apache License

public void responseRedirected(String url) {
    datastore.getHibernateTemplate().execute(new Closure<Object>(this) {
        @Override//  ww  w. ja  va2  s .  c om
        public Object call(Object... args) {
            Session session = (Session) args[0];
            if (!FlushMode.isManualFlushMode(session.getFlushMode())) {
                session.flush();
            }
            return null;
        }
    });
}

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

License:Apache License

@Override
protected void closeSession(Session session, SessionFactory sessionFactory) {
    if (!FlushMode.isManualFlushMode(session.getFlushMode())) {
        session.flush();/*from  w  ww. j  a v  a 2 s  .c  om*/
    }
    super.closeSession(session, sessionFactory);
}

From source file:org.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;/*  w w  w  .j  a v a 2 s .co  m*/
    }

    SessionHolder sessionHolder = (SessionHolder) TransactionSynchronizationManager
            .getResource(getSessionFactory());
    Session session = sessionHolder != null ? sessionHolder.getSession() : null;
    try {
        super.postHandle(request, model);
        if (session != null && getFlushMode() != GrailsHibernateTemplate.FLUSH_NEVER
                && !FlushMode.isManualFlushMode(session.getFlushMode())) {
            logger.debug("Eagerly flushing Hibernate session");
            session.flush();
        }
    } finally {
        if (session != null) {
            session.setFlushMode(FlushMode.MANUAL);
        }
    }
}

From source file:org.grails.orm.hibernate3.support.GrailsOpenSessionInViewInterceptor.java

License:Apache License

@Override
protected void flushIfNecessary(Session session, boolean existingTransaction) throws HibernateException {
    if (session != null && !FlushMode.isManualFlushMode(session.getFlushMode())) {
        super.flushIfNecessary(session, existingTransaction);
    }/*  www .j  a  v a2  s  .  c  o  m*/
}

From source file:org.grails.orm.hibernate4.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 va  2  s .  c om
    }

    SessionHolder sessionHolder = (SessionHolder) TransactionSynchronizationManager
            .getResource(getSessionFactory());
    Session session = sessionHolder != null ? sessionHolder.getSession() : null;
    try {
        super.postHandle(request, model);
        if (session != null && flushMode != AbstractHibernateDatastore.FlushMode.MANUAL
                && !FlushMode.isManualFlushMode(session.getFlushMode())) {
            logger.debug("Eagerly flushing Hibernate session");
            session.flush();
        }
    } finally {
        if (session != null) {
            session.setFlushMode(FlushMode.MANUAL);
        }
    }
}

From source file:org.hyperic.hq.events.server.session.AlertDefinitionDAO.java

License:Open Source License

/**
 * Find the alert def for a given appdef entity that is the child of the
 * parent alert def passed in, allowing for the query to return a stale copy
 * of the alert definition (for efficiency reasons).
 * /*from  w  w  w .  ja  v a2  s  .co  m*/
 * @param ent
 * @param parentId
 * @param allowStale <code>true</code> to allow stale copies of an alert
 *        definition in the query results; <code>false</code> to never allow
 *        stale copies, potentially always forcing a sync with the database.
 * @return The alert definition or <code>null</code>.
 */
public AlertDefinition findChildAlertDef(Resource res, Integer parentId, boolean allowStale) {
    Session session = this.getSession();
    FlushMode oldFlushMode = session.getFlushMode();

    try {
        if (allowStale) {
            session.setFlushMode(FlushMode.MANUAL);
        }

        return findChildAlertDef(res, parentId);
    } finally {
        session.setFlushMode(oldFlushMode);
    }
}

From source file:org.hyperic.hq.events.server.session.EventLogDAO.java

License:Open Source License

/**
 * Insert the event logs in batch, with batch size specified by the
 * <code>hibernate.jdbc.batch_size</code> configuration property.
 * //w  ww. ja  v  a2s .  c o  m
 * @param eventLogs The event logs to insert.
 */
void insertLogs(EventLog[] eventLogs) {
    Session session = getSession();

    FlushMode flushMode = session.getFlushMode();
    CacheMode cacheMode = session.getCacheMode();

    try {
        session.setFlushMode(FlushMode.MANUAL);

        // We do not want to update the 2nd level cache with these event
        // logs
        session.setCacheMode(CacheMode.IGNORE);

        for (int i = 0; i < eventLogs.length; i++) {
            create(eventLogs[i]);
        }

        session.flush();
        session.clear();
    } finally {
        session.setFlushMode(flushMode);
        session.setCacheMode(cacheMode);
    }
}