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:com.creative.dao.repository.GenericBatchDaoImplTest.java

License:Apache License

public void verifySession() {
    verify(hibernateParam.session).setCacheMode(CacheMode.IGNORE);
    verify(hibernateParam.session).setFlushMode(FlushMode.MANUAL);

}

From source file:com.eucalyptus.auth.euare.persist.DatabasePrincipalProvider.java

License:Open Source License

@Override
public UserPrincipal lookupPrincipalByAccessKeyId(final String keyId, final String nonce) throws AuthException {
    try (final TransactionResource tx = Entities.readOnlyDistinctTransactionFor(AccessKeyEntity.class)) {
        final UserEntity user;
        try {//from   ww w.ja  v a 2  s .c  o m
            user = (UserEntity) Entities.createCriteria(UserEntity.class).createCriteria("keys")
                    .add(Restrictions.eq("accessKey", keyId)).setFlushMode(FlushMode.MANUAL).setReadOnly(true)
                    .uniqueResult();
        } catch (Exception e) {
            throw new InvalidAccessKeyAuthException("Failed to find access key", e);
        }
        if (user == null) {
            throw new InvalidAccessKeyAuthException("Failed to find access key");
        }
        final UserPrincipal principal = new UserPrincipalImpl(user);
        final Optional<AccessKey> accessKey = Iterables.tryFind(principal.getKeys(),
                CollectionUtils.propertyPredicate(keyId, AccessKeys.accessKeyIdentifier()));
        if (!Iterables.any(accessKey.asSet(), AccessKeys.isActive())) {
            throw new InvalidAccessKeyAuthException("Invalid access key or token");
        }
        return decorateCredentials(principal, nonce, accessKey.get().getSecretKey());
    }
}

From source file:com.evolveum.midpoint.repo.sql.helpers.BaseHelper.java

License:Apache License

public Session beginTransaction(boolean readOnly) {
    Session session = getSessionFactory().openSession();
    session.beginTransaction();/*from w  w w  .  j a  v  a2 s.  c o m*/

    if (getConfiguration().getTransactionIsolation() == TransactionIsolation.SNAPSHOT) {
        LOGGER.trace("Setting transaction isolation level SNAPSHOT.");
        session.doWork(new Work() {
            @Override
            public void execute(Connection connection) throws SQLException {
                connection.createStatement().execute("SET TRANSACTION ISOLATION LEVEL SNAPSHOT");
            }
        });
    }

    if (readOnly) {
        // we don't want to flush changes during readonly transactions (they should never occur,
        // but if they occur transaction commit would still fail)
        session.setFlushMode(FlushMode.MANUAL);

        LOGGER.trace("Marking transaction as read only.");
        session.doWork(new Work() {
            @Override
            public void execute(Connection connection) throws SQLException {
                connection.createStatement().execute("SET TRANSACTION READ ONLY");
            }
        });
    }
    return session;
}

From source file:com.evolveum.midpoint.repo.sql.SqlBaseService.java

License:Apache License

protected Session beginTransaction(boolean readOnly) {
    Session session = getSessionFactory().openSession();
    session.beginTransaction();/*from   w w  w  .  j a  v a  2 s  .c o  m*/

    if (getConfiguration().getTransactionIsolation() == TransactionIsolation.SNAPSHOT) {
        LOGGER.trace("Setting transaction isolation level SNAPSHOT.");
        session.doWork(new Work() {
            @Override
            public void execute(Connection connection) throws SQLException {
                connection.createStatement().execute("SET TRANSACTION ISOLATION LEVEL SNAPSHOT");
            }
        });
    }

    if (readOnly) {
        // we don't want to flush changes during readonly transactions (they should never occur,
        // but if they occur transaction commit would still fail)
        session.setFlushMode(FlushMode.MANUAL);

        LOGGER.trace("Marking transaction as read only.");
        session.doWork(new Work() {
            @Override
            public void execute(Connection connection) throws SQLException {
                connection.createStatement().execute("SET TRANSACTION READ ONLY");
            }
        });
    }
    return session;
}

From source file:com.googlecode.hibernate.audit.synchronization.AuditProcess.java

License:Open Source License

public void doBeforeTransactionCompletion(SessionImplementor session) {
    if (workUnits.size() == 0) {
        return;/*from www  .ja  va 2 s  .c  om*/
    }

    if (!session.getTransactionCoordinator().isActive()) {
        log.debug(
                "Skipping hibernate-audit transaction hook due to non-active (most likely marked as rollback) transaction");
        return;
    }

    if (FlushMode.MANUAL == session.getHibernateFlushMode() || session.isClosed()) {
        Session temporarySession = null;
        try {
            temporarySession = session.sessionWithOptions().connection().autoClose(false)
                    .connectionHandlingMode(
                            PhysicalConnectionHandlingMode.DELAYED_ACQUISITION_AND_RELEASE_AFTER_TRANSACTION)
                    .openSession();
            executeInSession(temporarySession);
            temporarySession.flush();
        } finally {
            if (temporarySession != null) {
                temporarySession.close();
            }
        }
    } else {
        executeInSession(session);

        // explicitly flushing the session, as the auto-flush may have already happened.
        session.flush();
    }
}

From source file:com.idega.bedework.bussiness.CalintfImplIdega.java

public synchronized void open(final boolean webMode) throws CalFacadeException {
    if (isOpen) {
        throw new CalFacadeException("Already open");
    }/*from  w w w . jav a 2 s  .  co  m*/

    isOpen = true;

    if ((sess != null) && (!webMode)) {
        warn("Session is not null. Will close");
        try {
            close();
        } finally {
        }
    }

    if (sess == null) {
        if (debug) {
            debug("New hibernate session for " + objTimestamp);
        }
        sess = new HibSessionImpl();
        sess.init(getSessionFactory(), getLogger());
        if (webMode) {
            sess.setFlushMode(FlushMode.MANUAL);
        } else if (debug) {
            debug("Open session for " + objTimestamp);
        }
    }

    if (access != null) {
        access.open();
    }
}

From source file:com.ikon.servlet.admin.RebuildIndexesServlet.java

License:Open Source License

/**
 * FlushToIndexes implementation/*from www.j  av a2s .  c  om*/
 */
@SuppressWarnings("rawtypes")
private void luceneIndexesFlushToIndexes(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    log.debug("luceneIndexesFlushToIndexes({}, {})", request, response);
    PrintWriter out = response.getWriter();
    response.setContentType(MimeTypeConfig.MIME_HTML);
    header(out, "Rebuild Lucene indexes", breadcrumb);
    out.flush();

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

    try {
        Config.SYSTEM_MAINTENANCE = true;
        Config.SYSTEM_READONLY = true;
        out.println("<ul>");
        out.println("<li>System into maintenance mode</li>");
        FileLogger.info(BASE_NAME, "BEGIN - Rebuild Lucene indexes");

        session = HibernateUtil.getSessionFactory().openSession();
        ftSession = Search.getFullTextSession(session);
        ftSession.setFlushMode(FlushMode.MANUAL);
        ftSession.setCacheMode(CacheMode.IGNORE);
        tx = ftSession.beginTransaction();
        Map<String, Long> total = new HashMap<String, Long>();

        // Calculate number of entities
        for (Class cls : classes) {
            String nodeType = cls.getSimpleName();
            out.println("<li>Calculate " + nodeType + "</li>");
            out.flush();
            long partial = NodeBaseDAO.getInstance().getCount(nodeType);
            FileLogger.info(BASE_NAME, "Number of {0}: {1}", nodeType, partial);
            out.println("<li>Number of " + nodeType + ": " + partial + "</li>");
            out.flush();
            total.put(nodeType, partial);
        }

        // Rebuild indexes
        out.println("<li>Rebuilding indexes</li>");
        out.flush();

        // Scrollable results will avoid loading too many objects in memory
        for (Class cls : classes) {
            String nodeType = cls.getSimpleName();
            out.println("<li>Indexing " + nodeType + "</li>");
            out.flush();

            ProgressMonitor monitor = new ProgressMonitor(out, total.get(nodeType));
            ScrollableResults results = ftSession.createCriteria(cls)
                    .setFetchSize(Config.HIBERNATE_INDEXER_BATCH_SIZE_LOAD_OBJECTS)
                    .scroll(ScrollMode.FORWARD_ONLY);
            int index = 0;

            while (results.next()) {
                monitor.documentsAdded(1);
                ftSession.index(results.get(0)); // Index each element

                if (index++ % Config.HIBERNATE_INDEXER_BATCH_SIZE_LOAD_OBJECTS == 0) {
                    ftSession.flushToIndexes(); // Apply changes to indexes
                    ftSession.clear(); // Free memory since the queue is processed
                }
            }
        }

        tx.commit();

        Config.SYSTEM_READONLY = false;
        Config.SYSTEM_MAINTENANCE = false;
        out.println("<li>System out of maintenance mode</li>");
        out.flush();

        // Finalized
        FileLogger.info(BASE_NAME, "END - Rebuild Lucene indexes");
        out.println("<li>Index rebuilding completed!</li>");
        out.println("</ul>");
        out.flush();
    } catch (Exception e) {
        tx.rollback();
        out.println("<div class=\"warn\">Exception: " + e.getMessage() + "</div>");
        out.flush();
    } finally {
        HibernateUtil.close(ftSession);
        HibernateUtil.close(session);
    }

    // End page
    footer(out);
    out.flush();
    out.close();

    // Activity log
    UserActivity.log(request.getRemoteUser(), "ADMIN_FORCE_REBUILD_INDEXES", null, null, null);
    log.debug("luceneIndexesFlushToIndexes: void");
}

From source file:com.kanjiportal.portal.admin.LuceneManagementAction.java

License:Open Source License

public void reIndexKanji() {
    FullTextSession fullTextSession = (FullTextSession) entityManager.getDelegate();
    fullTextSession.setFlushMode(FlushMode.MANUAL);
    fullTextSession.setCacheMode(CacheMode.IGNORE);
    log.debug("Indexing kanjis ....");
    long beforeKanjis = System.currentTimeMillis();

    //Scrollable results will avoid loading too many objects in memory
    ScrollableResults results = fullTextSession.createCriteria(Kanji.class).setFetchSize(BATCH_SIZE)
            .setFetchMode("meanings", FetchMode.JOIN).setFetchMode("meanings.meaning.language", FetchMode.JOIN)
            .scroll(ScrollMode.FORWARD_ONLY);
    int index = 0;
    while (results.next()) {
        index++;//from  w  w w. j  a  v a 2  s .c om
        fullTextSession.index(results.get(0)); //index each element
        if (index % BATCH_SIZE == 0) {
            entityManager.flush();
            entityManager.clear();
            log.debug("flush()");
        }
    }

    log.debug("Indexing kanjis done");
    long afterKanjis = System.currentTimeMillis();

    facesMessages.add("Kanji Indexing done in #0 ms", afterKanjis - beforeKanjis);
}

From source file:com.kanjiportal.portal.admin.LuceneManagementAction.java

License:Open Source License

public void reIndexDictionary() {
    FullTextSession fullTextSession = (FullTextSession) entityManager.getDelegate();
    fullTextSession.setFlushMode(FlushMode.MANUAL);
    fullTextSession.setCacheMode(CacheMode.IGNORE);

    long beforeDictionary = System.currentTimeMillis();

    //Scrollable results will avoid loading too many objects in memory
    ScrollableResults results = fullTextSession.createCriteria(Dictionary.class).setFetchSize(BATCH_SIZE)
            .setFetchMode("translations", FetchMode.JOIN).setFetchMode("translations.language", FetchMode.JOIN)
            .scroll(ScrollMode.FORWARD_ONLY);
    int index = 0;
    while (results.next()) {
        index++;// w w w  .  j  a v  a2s .  c o  m
        fullTextSession.index(results.get(0)); //index each element
        if (index % BATCH_SIZE == 0) {
            entityManager.flush();
            entityManager.clear();
            log.debug("flush()");
        }
    }

    log.debug("Indexing dictionary done");
    long afterDictionary = System.currentTimeMillis();

    facesMessages.add("Dictionary Indexing done in #0 ms", afterDictionary - beforeDictionary);
}

From source file:com.mtech.easyexchange.SessionFactoryProvider.java

License:Open Source License

public static Session openSession() {
    Session session = sessionFactory.openSession();
    session.setFlushMode(FlushMode.MANUAL);

    ManagedSessionContext.bind(session);

    return session;
}