Example usage for org.hibernate FlushMode AUTO

List of usage examples for org.hibernate FlushMode AUTO

Introduction

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

Prototype

FlushMode AUTO

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

Click Source Link

Document

The Session is sometimes flushed before query execution in order to ensure that queries never return stale state.

Usage

From source file:org.jboss.seam.persistence.hibernate.test.ManagedHibernateSessionFlushModeTestBase.java

License:Open Source License

@Test
public void testChangedTouchedSessionFlushMode() {
    try {//from  ww  w.  jav  a 2  s .co m
        session.setFlushMode(FlushMode.AUTO);
        pc.changeFlushMode(FlushModeType.MANUAL);
        Assert.assertEquals(FlushMode.MANUAL, session.getFlushMode());
    } finally {
        session.setFlushMode(FlushMode.AUTO);
    }
}

From source file:org.jooby.hbm.OpenSessionInView.java

License:Apache License

@Override
public void handle(final Request req, final Response rsp, final Chain chain) throws Throwable {
    SessionFactory sf = emf.getSessionFactory();

    EntityManager em = emf.createEntityManager();
    Session session = (Session) em.getDelegate();
    String sessionId = Integer.toHexString(System.identityHashCode(session));
    keys.forEach(key -> req.set(key, em));

    log.debug("session opened: {}", sessionId);
    TrxResponse trxrsp = new TrxResponse(rsp, em);
    try {/*from w  w w.j a v  a2 s.c  o  m*/
        log.debug("  [{}] binding", sessionId);
        ManagedSessionContext.bind(session);

        FlushMode flushMode = FlushMode.AUTO;
        log.debug("  [{}] flush mode: {}", sessionId, flushMode);
        session.setFlushMode(flushMode);

        trxrsp.begin();

        // invoke next handler
        chain.next(req, trxrsp);
    } catch (Exception ex) {
        trxrsp.setRollbackOnly();
        throw ex;
    } finally {
        trxrsp.done();
        log.debug("  [{}] unbinding", sessionId);
        ManagedSessionContext.unbind(sf);
        log.debug("session released: [{}]", sessionId);
    }
}

From source file:org.jooby.internal.hbm.RootUnitOfWork.java

License:Apache License

public RootUnitOfWork(final Session session) {
    super(session);
    bind(session);
    session.setHibernateFlushMode(FlushMode.AUTO);
}

From source file:org.kaaproject.kaa.server.common.dao.impl.sql.HibernateAbstractDao.java

License:Apache License

@Override
public Session getSession() {
    return getSession(FlushMode.AUTO);
}

From source file:org.mifos.framework.persistence.LegacyGenericDao.java

License:Open Source License

public Object execUniqueResultNamedQueryWithoutFlush(final String queryName,
        final Map<String, ?> queryParameters) throws PersistenceException {
    try {/*from   w  ww  .j a v  a2s  .co  m*/
        Session sess = getSession();
        sess.setFlushMode(FlushMode.MANUAL);
        Query query = getSession().getNamedQuery(queryName);
        logger.debug("The query object for the query with the name  " + queryName + " has been obtained");
        query.setProperties(queryParameters);
        Object returnObject = query.uniqueResult();
        sess.setFlushMode(FlushMode.AUTO);
        return returnObject;
    } catch (GenericJDBCException gje) {
        throw new ConnectionNotFoundException(gje);
    } catch (Exception e) {
        throw new PersistenceException(e);
    }
}

From source file:org.olat.core.commons.services.mark.impl.MarkManagerImpl.java

License:Apache License

@Override
public void moveMarks(OLATResourceable ores, String oldSubPath, String newSubPath) {
    // can be a lot of marks to move around
    StringBuilder sb = new StringBuilder();
    sb.append("update ").append(MarkImpl.class.getName()).append(" mark set mark.resSubPath=:newSubPath ")
            .append("where mark.resId=:resId and mark.resName=:resName and mark.resSubPath=:oldSubPath");

    DBQuery query = DBFactory.getInstance().createQuery(sb.toString());
    query.setString("resName", ores.getResourceableTypeName());
    query.setLong("resId", ores.getResourceableId());
    query.setString("oldSubPath", oldSubPath);
    query.setString("newSubPath", newSubPath);
    query.executeUpdate(FlushMode.AUTO);
}

From source file:org.olat.core.commons.services.mark.impl.MarkManagerImpl.java

License:Apache License

@Override
public void deleteMark(OLATResourceable ores) {
    StringBuilder sb = new StringBuilder();
    sb.append("delete from ").append(MarkImpl.class.getName()).append(" mark where ")
            .append("mark.resId=:resId and mark.resName=:resName");

    DBQuery query = DBFactory.getInstance().createQuery(sb.toString());
    query.setString("resName", ores.getResourceableTypeName());
    query.setLong("resId", ores.getResourceableId());
    query.executeUpdate(FlushMode.AUTO);
}

From source file:org.olat.core.commons.services.mark.impl.MarkManagerImpl.java

License:Apache License

@Override
public void deleteMark(OLATResourceable ores, String subPath) {
    StringBuilder sb = new StringBuilder();
    sb.append("delete from ").append(MarkImpl.class.getName()).append(" mark where ")
            .append("mark.resId=:resId and mark.resName=:resName and mark.resSubPath=:resSubPath");

    DBQuery query = DBFactory.getInstance().createQuery(sb.toString());
    query.setString("resName", ores.getResourceableTypeName());
    query.setLong("resId", ores.getResourceableId());
    query.setString("resSubPath", subPath);
    query.executeUpdate(FlushMode.AUTO);
}

From source file:org.olat.core.commons.services.notifications.manager.NotificationsManagerImpl.java

License:Apache License

/**
 * deletes all publishers of the given olatresourceable. e.g. ores =
 * businessgroup 123 -> deletes possible publishers: of Folder(toolfolder), of
 * Forum(toolforum)/* ww  w.  j av  a2  s .co  m*/
 * 
 * @param ores
 */
public void deletePublishersOf(OLATResourceable ores) {
    String type = ores.getResourceableTypeName();
    Long id = ores.getResourceableId();
    if (type == null || id == null)
        throw new AssertException("type/id cannot be null! type:" + type + " / id:" + id);
    List<Publisher> pubs = getPublishers(type, id);
    if (pubs.isEmpty())
        return;

    String q1 = "delete from notisub sub where sub.publisher in (:publishers)";
    DBQuery query1 = dbInstance.createQuery(q1);
    query1.setParameterList("publishers", pubs);
    query1.executeUpdate(FlushMode.AUTO);

    String q2 = "delete from notipublisher pub where pub in (:publishers)";
    DBQuery query2 = dbInstance.createQuery(q2);
    query2.setParameterList("publishers", pubs);
    query2.executeUpdate(FlushMode.AUTO);
}

From source file:org.olat.core.logging.activity.UserActivityLoggerImpl.java

License:Apache License

@Override
public void log(ILoggingAction loggingAction, Class<?> callingClass, ILoggingResourceable... lriOrNull) {
    final ActionType actionType = stickyActionType_ != null ? stickyActionType_
            : loggingAction.getResourceActionType();

    // don't log entries with loggingAction type 'tracking'
    if (isLogAnonymous_ && actionType.equals(ActionType.tracking)) {
        return;/* w w  w . j a  va2  s  .  c  o  m*/
    }

    // fetch some of the loggingAction fields - used for error logging below
    final CrudAction crudAction = loggingAction.getCrudAction();
    final ActionVerb actionVerb = loggingAction.getActionVerb();
    final String actionObject = loggingAction.getActionObject();

    // calculate the combined and ordered list of LoggingResourceables which should go
    // to the database below right away
    List<ILoggingResourceable> resourceInfos = getCombinedOrderedLoggingResourceables(lriOrNull);

    if (loggingAction.getTypeListDefinition() == null) {
        // this is a foul!
        log_.warn("LoggingAction has no ResourceableTypeList defined: action=" + loggingAction + ", fieldId="
                + loggingAction.getJavaFieldIdForDebug());
    } else {
        // good boy
        String errorMsg = loggingAction.getTypeListDefinition().executeCheckAndGetErrorMessage(resourceInfos);
        if (errorMsg != null) {
            // we found an inconsistency
            // lets make this a warn
            log_.warn(
                    "LoggingAction reported an inconsistency: " + loggingAction.getActionVerb() + " "
                            + loggingAction.getActionObject() + ", action=" + loggingAction + ", fieldId="
                            + loggingAction.getJavaFieldIdForDebug() + ", expected: "
                            + loggingAction.getTypeListDefinition().toString() + ", actual: "
                            + convertLoggingResourceableListToString(resourceInfos),
                    new Exception("OLAT-4653"));
        }
    }

    if (session_ == null) {
        // then I can't log - log information without session/user information isn't of much use
        // issue a log warn with a stacktrace for this
        log_.error("No session available to UserActivityLogger. Cannot write log entry: " + crudAction.name()
                + ":" + actionVerb.name() + ", " + actionObject + ", "
                + convertLoggingResourceableListToString(resourceInfos), new Exception());
        return;
    }

    if (session_.getSessionInfo() == null || session_.getSessionInfo().getSession() == null
            || session_.getSessionInfo().getSession().getId() == null
            || session_.getSessionInfo().getSession().getId().length() == 0) {
        // no session Id available - odd
        log_.error("No session information available to UserActivityLogger. Cannot write log entry: "
                + crudAction.name() + ":" + actionVerb.name() + ", " + actionObject + ", "
                + convertLoggingResourceableListToString(resourceInfos), new Exception());
        return;
    }
    final String sessionId = session_.getSessionInfo().getSession().getId();

    Identity identity = session_.getIdentity();
    if (identity == null) {
        // no identity available - odd
        log_.error("No identity available to UserActivityLogger. Cannot write log entry: " + crudAction.name()
                + ":" + actionVerb.name() + ", " + actionObject + ", "
                + convertLoggingResourceableListToString(resourceInfos), new Exception());
        return;
    }

    Long identityKey = identity.getKey();

    if (actionType != ActionType.admin) {
        final String identityKeyStr = String.valueOf(identityKey);
        for (Iterator it = resourceInfos.iterator(); it.hasNext();) {
            ILoggingResourceable lr = (ILoggingResourceable) it.next();
            if (lr.getResourceableType() == StringResourceableType.targetIdentity) {
                if (log_.isDebug() && !lr.getId().equals(identityKeyStr)) {
                    // complain
                    final Writer strackTraceAsStringWriter = new StringWriter();
                    final PrintWriter printWriter = new PrintWriter(strackTraceAsStringWriter);
                    (new Exception("OLAT-4955 debug stacktrac")).printStackTrace(printWriter);
                    log_.debug(
                            "OLAT-4955: Not storing targetIdentity for non-admin logging actions. A non-admin logging action wanted to store a user other than the one from the session: action="
                                    + loggingAction + ", fieldId=" + loggingAction.getJavaFieldIdForDebug(),
                            strackTraceAsStringWriter.toString());
                }
                // OLAT-4955: remove targetIdentity
                it.remove();
            }
        }
    }

    String identityName;
    if (isLogAnonymous_ && (actionType != ActionType.admin)) {
        identityName = "";
    } else {
        identityName = identity.getName();
    }

    // start creating the LoggingObject
    final LoggingObject logObj = new LoggingObject(sessionId, identityKey, identityName,
            crudAction.name().substring(0, 1), actionVerb.name(), actionObject);

    // do simpleDuration calculation & storing
    LoggingObject lastLogObj = (LoggingObject) session_.getEntry(USESS_KEY_USER_ACTIVITY_LOGGING_LAST_LOG);
    if (lastLogObj != null) {
        // lastLogObj = (LoggingObject) DBFactory.getInstance().loadObject(lastLogObj);
        // DBFactory.getInstance().updateObject(lastLogObj);
        // Implementation Note:
        // we used to do loadObject(), updateObject() here - which is the preferred best practice hibernate way
        // for changing an existing object in the database.
        // in the setup @UZH we'll use BLACKHOLE as the storage engine for the o_loggingtable (this is to have
        // minimal work load on the Main OLAT DB and not have duplicate data on the Main OLAT DB and the Logging DB).
        // Using BLACKHOLE results in the 'lastLogObj' here, not to exist in the database anymore.
        // Hence we can't do a loadObject() nor an updateObject(). The latter does not work due to the fact
        // that Hibernate checks the number of updated rows and expect that to equal 1 - which is not the case
        // when using BLACKHOLE.

        // Workaround: - also compare with LoggingObject.hbm.xml docu
        //
        // We use the sql-update's feature check="none", which disables the above mentioned check.
        // Using this in combination with manual SQL code below seems to be the only feasible way
        // to have Hibernate not do any row-number-checks.

        // Implications of the workaround:
        //
        // * Manual SQL: It shouldn't be a big deal to have this manual SQL code as it is very standard.
        // * CANT USE updateObject(LoggingObject) EVER:
        // @TODO We might have to add a check which verifies that no one calls updateObject(LoggingObject)
        // if that would be called it would simply fail in the BLACKHOLE@UZH setup

        // calculate the duration - take the simple diff of the two creationDate fields
        Date currentTime = logObj.getCreationDate();
        Date lastTime = lastLogObj.getCreationDate();
        long duration;
        if (lastTime == null) {
            duration = -1;
        } else if (currentTime == null) {
            duration = System.currentTimeMillis() - lastTime.getTime();
        } else {
            duration = currentTime.getTime() - lastTime.getTime();
        }

        DB db = DBFactory.getInstanceForClosing();
        if (db != null && db.isError()) {
            // then we would run into an ERROR when we'd do more with this DB
            // hence we just issue a log.info here with the details
            // @TODO: lower to log_.info once we checked that it doesn't occur very often (best for 6.4)
            log_.warn(
                    "log: DB is in Error state therefore the UserActivityLoggerImpl cannot update the simpleDuration of log_id "
                            + lastLogObj.getKey() + " with value " + duration + ", loggingObject: "
                            + lastLogObj);
        } else {
            DBQuery update = DBFactory.getInstance().createQuery(
                    "update org.olat.core.logging.activity.LoggingObject set simpleDuration = :duration where log_id = :logid");
            update.setLong("duration", duration);
            update.setLong("logid", lastLogObj.getKey());
            // we have to do FlushMode.AUTO (which is the default anyway)
            update.executeUpdate(FlushMode.AUTO);
        }
    }

    // store the current logging object in the session - for duration calculation at next log
    session_.putEntry(USESS_KEY_USER_ACTIVITY_LOGGING_LAST_LOG, logObj);

    if (resourceInfos != null && resourceInfos.size() != 0) {
        // this should be the normal case - we do have LoggingResourceables which we can log
        // alongside the log message

        // check if we have more than 4 - if we do, issue a log and remove the middle ones
        if (resourceInfos.size() > 4) {
            log_.warn("More than 4 resource infos set on a user activity log. Can only have 4. Having: "
                    + resourceInfos.size());
            int diff = resourceInfos.size() - 4;
            for (int i = 0; i < diff; i++) {
                resourceInfos.remove(3);
            }
        }

        // get the target resourceable
        ILoggingResourceable ri = resourceInfos.get(resourceInfos.size() - 1);
        logObj.setTargetResourceInfo(ri);

        // now set parent - if applicable
        if (resourceInfos.size() > 1) {
            ri = resourceInfos.get(resourceInfos.size() - 2);
            logObj.setParentResourceInfo(ri);
        }

        // and set the grand parent - if applicable
        if (resourceInfos.size() > 2) {
            ri = resourceInfos.get(resourceInfos.size() - 3);
            logObj.setGrandParentResourceInfo(ri);
        }

        // and set the great grand parent - if applicable
        if (resourceInfos.size() > 3) {
            ri = resourceInfos.get(resourceInfos.size() - 4);
            logObj.setGreatGrandParentResourceInfo(ri);
        }
    }

    // fill the remaining fields
    logObj.setBusinessPath(businessPath_);
    logObj.setSourceClass(callingClass.getCanonicalName());
    logObj.setSimpleDuration(-1);
    logObj.setResourceAdminAction(actionType.equals(ActionType.admin) ? true : false);
    Locale locale = I18nManager.getInstance()
            .getLocaleOrDefault(identity.getUser().getPreferences().getLanguage());

    // prepate the user properties, set them at once
    List<String> tmpUserProperties = new ArrayList<String>(12);
    for (Iterator<String> iterator = userProperties_.iterator(); iterator.hasNext();) {
        String userPropString = identity.getUser().getPropertyOrIdentityEnvAttribute(iterator.next(), locale);
        boolean shorten = false;
        try {
            if (userPropString != null && userPropString.getBytes("UTF-8").length > 254) {
                shorten = true;
            }
        } catch (UnsupportedEncodingException uee) {
            log_.error("error while calculating real string length: unsupported encoding: ", uee);
            shorten = true;
        }
        if (shorten) {
            log_.error(
                    "Userproperty was too long for logging-table (shortened automatically). check that nothing valueable is lost! value before cut: "
                            + userPropString);
            userPropString = userPropString.substring(0, 255);
        }
        tmpUserProperties.add(userPropString);
    }
    logObj.setUserProperties(tmpUserProperties);

    // and store it
    DB db = DBFactory.getInstanceForClosing();
    if (db != null && db.isError()) {
        // then we would run into an ERROR when we'd do more with this DB
        // hence we just issue a log.info here with the details
        // @TODO: lower to log_.info once we checked that it doesn't occur very often (best for 6.4)
        log_.warn(
                "log: DB is in Error state therefore the UserActivityLoggerImpl cannot store the following logging action into the loggingtable: "
                        + logObj);
    } else {
        DBFactory.getInstance().saveObject(logObj);
    }
}