Example usage for org.hibernate CacheMode NORMAL

List of usage examples for org.hibernate CacheMode NORMAL

Introduction

In this page you can find the example usage for org.hibernate CacheMode NORMAL.

Prototype

CacheMode NORMAL

To view the source code for org.hibernate CacheMode NORMAL.

Click Source Link

Document

The session may read items from the cache, and add items to the cache.

Usage

From source file:at.itbh.bev.DataUpdateBean.java

License:Open Source License

/**
 * Create or refresh the spatial search index based on the address data in
 * the database.//from ww w.j a  v a2  s .c om
 * @return 
 * @return 
 */
@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
//   @TransactionTimeout(value = 2, unit = TimeUnit.HOURS)
public Long rebuildIndex() {
    Long startTime = System.currentTimeMillis();

    if (rebuildRunning) {
        logger.warn(
                "There is already an rebuild operation running. Only one rebuild operation is allowed at a time.");
        throw new EJBException(
                "There is already an rebuild operation running. Only one rebuild operation is allowed at a time.");
    }

    rebuildRunning = true;
    try {
        logger.info("Start the mass index rebuild.");

        FullTextEntityManager searchEm = Search.getFullTextEntityManager(em);
        searchEm.createIndexer(AdresseDenormalized.class).batchSizeToLoadObjects(1000)
                .cacheMode(CacheMode.NORMAL).threadsToLoadObjects(12).idFetchSize(1000)
                .progressMonitor(new SimpleIndexingProgressMonitor(100000)).transactionTimeout(7200)
                .startAndWait();

        rebuildRunning = false;
        logger.info("Finished the mass index rebuild.");
    } catch (Exception e) {
        rebuildRunning = false;
        context.setRollbackOnly();
        logger.errorf("Exception while updating the search index: '%s'", e.getMessage());
        throw new EJBException(e);
    } finally {
        rebuildRunning = false;
    }
    return System.currentTimeMillis() - startTime;
}

From source file:com.astonish.dropwizard.routing.hibernate.RoutingUnitOfWorkRequestDispatcherTest.java

License:Apache License

@Before
public void setUp() throws Exception {
    when(unitOfWork.readOnly()).thenReturn(false);
    when(unitOfWork.cacheMode()).thenReturn(CacheMode.NORMAL);
    when(unitOfWork.flushMode()).thenReturn(FlushMode.AUTO);
    when(unitOfWork.transactional()).thenReturn(true);

    when(sessionFactory.openSession()).thenReturn(session);
    when(session.getSessionFactory()).thenReturn(sessionFactory);
    when(session.beginTransaction()).thenReturn(transaction);
    when(session.getTransaction()).thenReturn(transaction);

    when(context.getRequest()).thenReturn(requestContext);

    when(transaction.isActive()).thenReturn(true);

    mockStatic(RouteStore.class);
    when(RouteStore.getInstance()).thenReturn(routeStore);
    when(routeStore.getRoute()).thenReturn("factory");
}

From source file:com.hack23.cia.service.data.impl.AbstractGenericDAOImpl.java

License:Apache License

/**
 * Adds the cache hints./*  w w w  . j a v  a  2s .  c  om*/
 *
 * @param typedQuery
 *            the typed query
 * @param comment
 *            the comment
 */
protected final void addCacheHints(final TypedQuery<?> typedQuery, final String comment) {
    typedQuery.setHint("org.hibernate.cacheMode", CacheMode.NORMAL);
    typedQuery.setHint("org.hibernate.cacheable", Boolean.TRUE);
    typedQuery.setHint("org.hibernate.comment", comment);
}

From source file:com.hack23.cia.service.data.impl.DataViewerImpl.java

License:Apache License

/**
 * Adds the cache hints.//from   w  w  w .  ja  va 2s. c om
 *
 * @param typedQuery
 *            the typed query
 * @param comment
 *            the comment
 */
private static void addCacheHints(final TypedQuery<?> typedQuery, final String comment) {
    typedQuery.setHint("org.hibernate.cacheMode", CacheMode.NORMAL);
    typedQuery.setHint("org.hibernate.cacheable", Boolean.TRUE);
    typedQuery.setHint("org.hibernate.comment", comment);
}

From source file:com.heliosapm.aa4h.parser.XMLQueryParser.java

License:Apache License

/**
 * Initializes a Criteria Query./*from w  ww. j av a  2 s .  c  o  m*/
 * Mandatory Attributes:<ul>
 * <li><b>name</b>: The unqualified class name driving the criteria query.</li>
 * </ul>
 * Optional Attributes:<ul>
 * <li><b>prefix</b>: The package name of the class driving the criteria query. If null, no package is assumed.</li>
 * <li><b>maxSize</b>: The maximum number of rows to return from the database.</li>
 * <li><b>fetchSize</b>: The number of rows to fetch when rows are requested. Usually not useful for AA4H.</li>
 * <li><b>cacheEnabled</b>: Enables or disables caching for the queried objects.</li>
 * <li><b>cacheMode</b>: The cache options for the queried objects.</li>
 * <li><b>flushMode</b>: The session flush options.</li>
 * <li><b>fetchMode</b>: The collection fetch options for the query.</li>
 * <li><b>lockMode</b>: The row lock options for the queried rows.</li>
 * <li><b>timeOut</b>: The query timeout option.</li>
 * <li><b>rowCountOnly</b>: Returns a count of the query rows only.</li>
 * </ul>
 * @param attrs The attributes of the processed node.
 * @return An appended or new CriteriaSpecification
 * @throws SAXException
 */
protected CriteriaSpecification processCriteria(Attributes attrs) throws SAXException {
    if (inDetached) {
        return criteriaStack.peek();
    }
    String name = attrs.getValue("name");
    String prefix = attrs.getValue("prefix");
    if (prefix != null) {
        className = prefix + "." + name;
    } else {
        className = name;
    }
    String maxSize = attrs.getValue("maxSize");
    String fetchSize = attrs.getValue("fetchSize");
    String firstResult = attrs.getValue("firstResult");
    String cacheEnabled = attrs.getValue("cacheEnabled");
    String cacheMode = attrs.getValue("cacheMode");
    String flushMode = attrs.getValue("flushMode");
    String fetchMode = attrs.getValue("fetchMode");
    String lockMode = attrs.getValue("lockMode");
    String timeOut = attrs.getValue("timeOut");
    String rowCountOnly = attrs.getValue("rowCountOnly");
    Criteria newCriteria = null;
    try {
        if (criteriaStack.size() == 0) {
            newCriteria = session.createCriteria(className);
        } else {
            newCriteria = ((Criteria) criteriaStack.peek()).createCriteria(className);
        }
        criteriaStack.push(newCriteria);
        if ("true".equalsIgnoreCase(rowCountOnly)) {
            newCriteria.setProjection(Projections.projectionList().add(Projections.rowCount())

            );
            setRowCountOnly(true);
        }
        if (maxSize != null && isRowCountOnly() == false) {
            newCriteria.setMaxResults(Integer.parseInt(maxSize));
        }
        if (fetchSize != null && isRowCountOnly() == false) {
            newCriteria.setFetchSize(Integer.parseInt(fetchSize));
        }
        if (firstResult != null && isRowCountOnly() == false) {
            newCriteria.setFirstResult(Integer.parseInt(firstResult));
        }
        if (timeOut != null) {
            newCriteria.setTimeout(Integer.parseInt(timeOut));
        }

        if ("true".equalsIgnoreCase(cacheEnabled)) {
            newCriteria.setCacheable(true);
        } else if ("false".equalsIgnoreCase(cacheEnabled)) {
            newCriteria.setCacheable(false);
        }
        if (fetchMode != null && fetchMode.length() > 0) {
            if ("JOIN".equalsIgnoreCase(fetchMode)) {
                newCriteria.setFetchMode(name, FetchMode.JOIN);
            } else if ("SELECT".equalsIgnoreCase(fetchMode)) {
                newCriteria.setFetchMode(name, FetchMode.SELECT);
            } else {
                newCriteria.setFetchMode(name, FetchMode.DEFAULT);
            }
        } else {
            newCriteria.setFetchMode(name, FetchMode.DEFAULT);
        }
        if (cacheMode != null && cacheMode.length() > 0) {
            if ("GET".equalsIgnoreCase(cacheMode)) {
                newCriteria.setCacheMode(CacheMode.GET);
            } else if ("IGNORE".equalsIgnoreCase(cacheMode)) {
                newCriteria.setCacheMode(CacheMode.IGNORE);
            } else if ("NORMAL".equalsIgnoreCase(cacheMode)) {
                newCriteria.setCacheMode(CacheMode.NORMAL);
            } else if ("PUT".equalsIgnoreCase(cacheMode)) {
                newCriteria.setCacheMode(CacheMode.PUT);
            } else if ("REFRESH".equalsIgnoreCase(cacheMode)) {
                newCriteria.setCacheMode(CacheMode.REFRESH);
            } else {
                newCriteria.setCacheMode(CacheMode.NORMAL);
            }
        }
        if (lockMode != null && lockMode.length() > 0) {
            if ("NONE".equalsIgnoreCase(lockMode)) {
                newCriteria.setLockMode(LockMode.NONE);
            } else if ("READ".equalsIgnoreCase(lockMode)) {
                newCriteria.setLockMode(LockMode.READ);
            } else if ("UPGRADE".equalsIgnoreCase(lockMode)) {
                newCriteria.setLockMode(LockMode.UPGRADE);
            } else if ("UPGRADE_NOWAIT".equalsIgnoreCase(lockMode)) {
                newCriteria.setLockMode(LockMode.UPGRADE_NOWAIT);
            } else if ("WRITE".equalsIgnoreCase(lockMode)) {
                newCriteria.setLockMode(LockMode.WRITE);
            } else {
                throw new SAXException("lockMode[" + lockMode + "] Not Recognized");
            }
        }
        if (flushMode != null && flushMode.length() > 0) {
            if ("ALWAYS".equalsIgnoreCase(flushMode)) {
                newCriteria.setFlushMode(FlushMode.ALWAYS);
            } else if ("AUTO".equalsIgnoreCase(flushMode)) {
                newCriteria.setFlushMode(FlushMode.AUTO);
            } else if ("COMMIT".equalsIgnoreCase(flushMode)) {
                newCriteria.setFlushMode(FlushMode.COMMIT);
            } else if ("NEVER".equalsIgnoreCase(flushMode)) {
                // NEVER is deprecated, so we won't throw an exception but we'll ignore it.
            } else {
                throw new SAXException("flushMode[" + flushMode + "] Not Recognized");
            }
        }
        return newCriteria;

    } catch (Exception e) {
        throw new SAXException("Unable to configure class " + className, e);
    }
}

From source file:com.ikon.dao.LanguageDAO.java

License:Open Source License

/**
 * Find all languages//w ww.  ja  va2 s . c om
 */
public static List<Language> findAll() throws DatabaseException {
    return findAll(CacheMode.NORMAL);
}

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

License:Open Source License

/**
 * MassIndexer implementation.//from ww w.  j  av a  2 s .  c  o  m
 */
@SuppressWarnings("rawtypes")
private void luceneIndexesMassIndexer(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    log.debug("luceneIndexesMassIndexer({}, {})", 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;

    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);
        long total = 0;

        // 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 += partial;
        }

        // Rebuild indexes
        out.println("<li>Rebuilding indexes</li>");
        out.flush();
        ProgressMonitor monitor = new ProgressMonitor(out, (int) total);
        ftSession.createIndexer().batchSizeToLoadObjects(Config.HIBERNATE_INDEXER_BATCH_SIZE_LOAD_OBJECTS)
                .threadsForSubsequentFetching(Config.HIBERNATE_INDEXER_THREADS_SUBSEQUENT_FETCHING)
                .threadsToLoadObjects(Config.HIBERNATE_INDEXER_THREADS_LOAD_OBJECTS)
                .threadsForIndexWriter(Config.HIBERNATE_INDEXER_THREADS_INDEX_WRITER)
                .cacheMode(CacheMode.NORMAL) // defaults to CacheMode.IGNORE
                .progressMonitor(monitor).startAndWait();

        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) {
        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("luceneIndexesMassIndexer: void");
}

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

License:Open Source License

/**
 * MassIndexer implementation.// www.j  ava  2 s.  c o m
 */
@SuppressWarnings("rawtypes")
private void luceneIndexesMassIndexer(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    log.debug("luceneIndexesMassIndexer({}, {})", 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;

    // Activity log
    UserActivity.log(request.getRemoteUser(), "ADMIN_FORCE_REBUILD_INDEXES", null, null, 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);
        long total = 0;

        // 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 += partial;
        }

        // Rebuild indexes
        out.println("<li>Rebuilding indexes</li>");
        out.flush();
        ProgressMonitor monitor = new ProgressMonitor(out, "NodeBase", (int) total);
        ftSession.createIndexer().batchSizeToLoadObjects(Config.HIBERNATE_INDEXER_BATCH_SIZE_LOAD_OBJECTS)
                .threadsForSubsequentFetching(Config.HIBERNATE_INDEXER_THREADS_SUBSEQUENT_FETCHING)
                .threadsToLoadObjects(Config.HIBERNATE_INDEXER_THREADS_LOAD_OBJECTS)
                .threadsForIndexWriter(Config.HIBERNATE_INDEXER_THREADS_INDEX_WRITER)
                .cacheMode(CacheMode.NORMAL) // defaults to CacheMode.IGNORE
                .progressMonitor(monitor).startAndWait();

        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) {
        out.println("<div class=\"warn\">Exception: " + e.getMessage() + "</div>");
        out.flush();
    } finally {
        Config.SYSTEM_READONLY = false;
        Config.SYSTEM_MAINTENANCE = false;
        HibernateUtil.close(ftSession);
        HibernateUtil.close(session);
    }

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

    log.debug("luceneIndexesMassIndexer: void");
}

From source file:de.innovationgate.webgate.api.jdbc.WGDatabaseImpl.java

License:Open Source License

public boolean commitTransaction() throws WGAPIException {
    Transaction transaction = getSession().getTransaction();
    if (transaction != null) {
        transaction.commit();//  ww  w .j a  va 2  s.  c  o  m
        getSession().setCacheMode(CacheMode.NORMAL);
        _db.getSessionContext().resetTransactionMode();
        getSession().beginTransaction();
        return true;
    }
    return false;
}

From source file:de.innovationgate.webgate.api.jdbc.WGDatabaseImpl.java

License:Open Source License

public boolean rollbackTransaction() throws WGAPIException {
    Transaction transaction = getSession().getTransaction();
    if (transaction != null && transaction.isActive()) {
        transaction.rollback();// w ww .  ja v a  2  s .c o  m
        getSession().setCacheMode(CacheMode.NORMAL);
        _db.getSessionContext().resetTransactionMode();
        getSession().beginTransaction();
        return true;
    }
    return false;
}