Example usage for org.hibernate FlushMode COMMIT

List of usage examples for org.hibernate FlushMode COMMIT

Introduction

In this page you can find the example usage for org.hibernate FlushMode COMMIT.

Prototype

FlushMode COMMIT

To view the source code for org.hibernate FlushMode COMMIT.

Click Source Link

Document

The Session is flushed when Transaction#commit is called.

Usage

From source file:org.openbravo.dal.core.SessionHandler.java

License:Open Source License

/**
 * Starts a transaction.// ww  w .  java 2  s . com
 */
protected void begin() {
    Check.isTrue(getSession() == null, "Session must be null before begin");
    setSession(createSession());
    getSession().setFlushMode(FlushMode.COMMIT);
    Check.isTrue(tx == null, "tx must be null before begin");
    tx = getSession().beginTransaction();
    log.debug("Transaction started");
}

From source file:org.openmrs.api.db.hibernate.HibernateTransactionManagerFlushOnCommit.java

License:Open Source License

/**
 * @see org.springframework.orm.hibernate3.HibernateTransactionManager#doBegin(java.lang.Object,
 *      org.springframework.transaction.TransactionDefinition)
 *//*  w w w.  j  a  va  2  s.  co  m*/
@Override
protected void doBegin(Object transaction, TransactionDefinition definition) {
    super.doBegin(transaction, definition);
    Session session = getSessionFactory().getCurrentSession();
    if (!session.getFlushMode().lessThan(FlushMode.COMMIT)) {
        session.setFlushMode(FlushMode.COMMIT);
    }
}

From source file:org.openmrs.module.patientportal.api.db.hibernate.HibernatePatientPortalReminderDAO.java

License:Open Source License

@Override
public PatientPortalReminder savePatientPortalReminder(PatientPortalReminder reminder) {
    log.debug("Save reminder - reminder.getFollowProcedure()=" + reminder.getFollowProcedure()
            + ", reminder.getFollowProcedureName() = " + reminder.getFollowProcedureName());

    if (reminder.getFollowProcedureName() != null) {
        reminder.setFollowProcedure(//from w  ww. j a  v a 2s  .co m
                Context.getConceptService().getConceptByName(reminder.getFollowProcedureName()));
        log.debug("New reminder.getFollowProcedure()=" + reminder.getFollowProcedure());
    }

    Session sess = sessionFactory.openSession();
    Transaction tx = sess.beginTransaction();
    sess.setFlushMode(FlushMode.COMMIT); // allow queries to return stale state
    sess.saveOrUpdate(reminder);
    tx.commit();
    //sess.flush();
    sess.close();
    //sessionFactory.getCurrentSession().saveOrUpdate(token);
    return reminder;
}

From source file:org.openmrs.module.patientportal.api.db.hibernate.HibernatePatientPortalReminderDAO.java

License:Open Source License

@Override
public void deletePatientPortalReminder(PatientPortalReminder reminder) {
    //sessionFactory.getCurrentSession().delete(token);
    //sessionFactory.getCurrentSession().close();
    Session sess = sessionFactory.openSession();
    Transaction tx = sess.beginTransaction();
    sess.setFlushMode(FlushMode.COMMIT); // allow queries to return stale state
    sess.delete(reminder);//  w  w  w  .j a  va  2  s  .  c om
    tx.commit();
    sess.close();

}

From source file:org.opentaps.search.IndexingService.java

License:Open Source License

/**
 * Creates the hibernate search index for a given Entity class.
 * @param fullTextSession a <code>FullTextSession</code> value
 * @param entityClass a <code>Class</code> value
 *///from w w w.  ja  v  a  2  s  .c  o  m
@SuppressWarnings("unchecked")
private void createIndexForEntity(FullTextSession fullTextSession, Class entityClass) {
    Criteria query = fullTextSession.createCriteria(entityClass)
            //load necessary associations
            .setFetchMode("distributor", FetchMode.JOIN)
            //distinct them (due to collection load)
            .setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY)
            //set flush mode, ensure it will write to disk on commit the transaction
            .setFlushMode(FlushMode.COMMIT)
            //minimize cache interaction
            .setCacheMode(CacheMode.IGNORE).setFetchSize(Session.FETCH_SIZE);
    //scroll in forward only
    ScrollableResults scroll = query.scroll(ScrollMode.FORWARD_ONLY);
    int batch = 0;
    while (scroll.next()) {
        batch++;
        fullTextSession.index(scroll.get(0));
        if (batch % Session.FETCH_SIZE == 0) {
            // batch flush index into session per FETCH_SIZE
            fullTextSession.flushToIndexes();
            fullTextSession.clear();
        }
    }
    // flush last changes
    fullTextSession.flushToIndexes();
    fullTextSession.getSearchFactory().optimize(entityClass);
}

From source file:org.opentaps.search.IndexingService.java

License:Open Source License

/** {@inheritDoc} */
@SuppressWarnings("unchecked")
public void createIndexForGenericEntity() throws ServiceException {

    if (value == null) {
        Debug.logError("Cannot create index for null value.", MODULE);
        return;/* w ww .  ja  v a 2  s.  c  om*/
    }

    Session session = null;
    FullTextSession fullTextSession = null;
    Transaction tx = null;

    try {
        // open a session
        session = getInfrastructure().getSession();
        // create FullTextSession by original hibernate session.
        fullTextSession = Search.getFullTextSession(session.getHibernateSession());
        fullTextSession.setFlushMode(FlushMode.COMMIT);
        fullTextSession.setCacheMode(CacheMode.IGNORE);

        tx = fullTextSession.beginTransaction();

        String entityName = value.getEntityName();
        ModelEntity modelEntity = value.getModelEntity();
        List<String> pkFieldNames = modelEntity.getPkFieldNames();

        Class cls = Class.forName("org.opentaps.base.entities." + entityName);
        Serializable id = null;

        if (pkFieldNames.size() > 1) {
            // multi fields pk
            Class pkCls = Class.forName("org.opentaps.base.entities." + entityName + "Pk");
            id = (Serializable) pkCls.newInstance();
            for (String pkFieldName : pkFieldNames) {
                HibernateUtil.setFieldValue(id, pkFieldName, value.get(pkFieldName));
            }
        } else if (pkFieldNames.size() == 1) {
            // simple field pk
            id = (Serializable) value.get(pkFieldNames.get(0));
        }

        Debug.logInfo("createIndexForGenericEntity: got id [" + id + "] for entity: " + entityName, MODULE);
        if (id != null) {
            Entity entity = (Entity) fullTextSession.get(cls, id);
            if (entity != null) {
                fullTextSession.index(entity);
            } else {
                fullTextSession.purge(cls, id);
            }
        }

        // flush last changes
        fullTextSession.flushToIndexes();
        fullTextSession.clear();
        tx.commit();
        Debug.logInfo("createIndexForGenericEntity: index committed", MODULE);
        if (session.isDirty()) {
            Debug.logWarning("Session still dirty ??", MODULE);
        }

    } catch (Exception e) {
        Debug.logError(e, MODULE);
        // rollback the transaction
        if (tx != null) {
            try {
                tx.rollback();
            } catch (Exception e2) {
                Debug.logWarning(e2, "Could not rollback the hibernate transaction on error.", MODULE);
            }
        }
        throw new ServiceException(e);
    } finally {
        // close the sessions
        try {
            if (fullTextSession != null) {
                fullTextSession.close();
            }
        } catch (Exception e) {
            Debug.logWarning(e, "Could not close the FullTextSession.", MODULE);
        }

        try {
            if (session != null && session.isOpen()) {
                Debug.logWarning("Session still open, closing.", MODULE);
                session.close();
            }
        } catch (Exception e) {
            Debug.logWarning(e, "Could not close the Session.", MODULE);
        }
    }
}

From source file:org.opentox.toxotis.persistence.db.DeleteTool.java

License:Open Source License

/**
 * Deletes a task of a given URI from the database (Note that this is different
 * from cancelling the task since it completely and permanently deletes the task
 * from the database).//from  ww w  . j  a v  a2s.  co  m
 * @param session
 * @param taskUri
 */
public int deleteTask(VRI taskUri) {
    Session session = getSession();
    session.setFlushMode(FlushMode.COMMIT);
    Transaction transaction = null;
    Task t = new Task(taskUri);
    t.setMeta(null);
    t.setCreatedBy(null);
    t.setResultUri(null);
    t.setStatus(null);
    t.setDuration(null);
    t.setErrorReport(null);
    t.setOntologicalClasses(null);
    try {
        transaction = session.beginTransaction();
        String sql = "DELETE FROM Task WHERE uri = ?";
        Query q = session.createSQLQuery(sql).setString(0, taskUri.toString());
        return q.executeUpdate();
    } catch (RuntimeException ex) {
        logger.warn("Deletion of task with URI " + taskUri
                + " failed. Logging the corresponding exception for details", ex);
        try {
            if (transaction != null) {
                transaction.rollback();
            }
        } catch (Throwable rte) {
            logger.error("Cannot rollback", rte);
        }
        throw ex;
    } finally {
        closeSession(session);
    }
}

From source file:org.opentox.toxotis.persistence.db.RegisterTool.java

License:Open Source License

public void storeUser(User user) {
    Session session = getSession();/*  w w  w  .  j a v  a2s.  c  om*/
    Transaction transaction = null;
    session.setFlushMode(FlushMode.COMMIT);
    try {
        transaction = session.beginTransaction();
        session.saveOrUpdate(user);
        transaction.commit();

        session.clear();
    } catch (RuntimeException ex) {
        logger.warn("Storage of User failed. Logging the corresponding exception for details", ex);
        try {
            if (transaction != null) {
                transaction.rollback();
            }
        } catch (Throwable rte) {
            logger.error("Cannot rollback", rte);
        }
        throw ex;
    } finally {
        closeSession(session);
    }
}

From source file:org.opentox.toxotis.persistence.db.RegisterTool.java

License:Open Source License

public void storeFeature(Feature feature) {
    Session session = getSession();//from w  w  w. j  a  v a  2s . co m
    Transaction transaction = null;
    session.setFlushMode(FlushMode.COMMIT);
    try {
        preprocessComponent(feature);
        transaction = session.beginTransaction();
        session.saveOrUpdate(feature);
        transaction.commit();
    } catch (RuntimeException ex) {
        logger.warn("Storage of Model failed. Logging the corresponding exception for details", ex);
        try {
            if (transaction != null) {
                transaction.rollback();
            }
        } catch (Throwable rte) {
            logger.error("Cannot rollback", rte);
        }
        throw ex;
    } finally {
        closeSession(session);
    }
}

From source file:org.opentox.toxotis.persistence.db.RegisterTool.java

License:Open Source License

public void storeModel(Model model) {
    Session session = getSession();//from   www .  j  ava2  s .co m
    Transaction transaction = null;
    session.setFlushMode(FlushMode.COMMIT);
    try {
        preprocessComponent(model);
        transaction = session.beginTransaction();

        session.evict(model.getAlgorithm());

        if (model.getParameters() != null) {
            for (Parameter p : model.getParameters()) {
                session.saveOrUpdate(p);
                session.flush();
                session.evict(p);
            }
        }

        if (model.getIndependentFeatures() != null) {
            for (Feature ft : model.getIndependentFeatures()) {
                storeFeature(ft);
                session.evict(ft);
            }
        }

        if (model.getCreatedBy() != null) {
            session.saveOrUpdate(model.getCreatedBy());
            session.flush();
            session.evict(model.getCreatedBy());
        }
        if (model.getDependentFeatures() != null) {
            for (Feature depFeature : model.getDependentFeatures()) {
                session.saveOrUpdate(depFeature);
                session.flush();
                session.evict(depFeature);
            }
        }

        if (model.getPredictedFeatures() != null) {
            for (Feature predictedFeature : model.getPredictedFeatures()) {
                session.saveOrUpdate(predictedFeature);
                session.flush();
                session.evict(predictedFeature);
            }
        }

        session.saveOrUpdate(model);
        transaction.commit();
        session.clear();
    } catch (StaleObjectStateException ex) {
        logger.error("Serious exception that cannot be recovered! Stale Object!!!!");
        try {
            if (session.getTransaction().isActive()) {
                session.getTransaction().rollback();
            }
        } catch (Throwable rte) {
            logger.error("Cannot rollback", rte);
        }
        throw ex;
    } catch (RuntimeException ex) {
        logger.warn("Storage of Model failed. Logging the corresponding exception for details", ex);
        try {
            if (transaction != null) {
                transaction.rollback();
            }
        } catch (Throwable rte) {
            logger.error("Cannot rollback", rte);
        }
        throw ex;
    } finally {
        closeSession(session);
    }
}