Example usage for org.hibernate ScrollMode FORWARD_ONLY

List of usage examples for org.hibernate ScrollMode FORWARD_ONLY

Introduction

In this page you can find the example usage for org.hibernate ScrollMode FORWARD_ONLY.

Prototype

ScrollMode FORWARD_ONLY

To view the source code for org.hibernate ScrollMode FORWARD_ONLY.

Click Source Link

Document

Requests a scrollable result that is only scrollable forwards.

Usage

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++;/*  w  w  w.j  a va 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  av a  2 s  . 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.knowbout.epg.entities.Program.java

License:Apache License

public static ScrollableResults selectAllShowsMoviesSports() {
    Session session = HibernateUtil.currentSession();
    Query query = session.getNamedQuery("Program.selectAllShowsMoviesSports");
    ScrollableResults scroll = query.scroll(ScrollMode.FORWARD_ONLY);
    return scroll;
}

From source file:com.knowbout.epg.entities.Program.java

License:Apache License

public static ScrollableResults selectAllTeams() {
    Session session = HibernateUtil.currentSession();
    Query query = session.getNamedQuery("Program.selectAllTeams");
    ScrollableResults scroll = query.scroll(ScrollMode.FORWARD_ONLY);
    return scroll;
}

From source file:com.leixl.easyframework.lucene.impl.LuceneEMovieDaoImpl.java

License:Open Source License

public Integer index(IndexWriter writer, Date startDate, Date endDate, Integer startId, Integer max)
        throws CorruptIndexException, IOException {
    Finder f = Finder.create("select bean from EMovie bean");

    f.append(" where 1=1");
    if (startId != null) {
        f.append(" and bean.id > :startId");
        f.setParam("startId", startId);
    }//w  ww. j a  v  a 2  s.c  o m
    if (startDate != null) {
        f.append(" and bean.createDate >= :startDate");
        f.setParam("startDate", startDate);
    }
    if (endDate != null) {
        f.append(" and bean.createDate <= :endDate");
        f.setParam("endDate", endDate);
    }
    f.append(" order by bean.id asc");
    if (max != null) {
        f.setMaxResults(max);
    }
    Session session = getSession();
    ScrollableResults movies = f.createQuery(getSession()).setCacheMode(CacheMode.IGNORE)
            .scroll(ScrollMode.FORWARD_ONLY);
    int count = 0;
    EMovie movie = null;
    while (movies.next()) {
        movie = (EMovie) movies.get(0);
        writer.addDocument(LuceneContent.createDocument(movie));
        if (++count % 20 == 0) {
            session.clear();
        }
    }
    if (count < max || movie == null) {
        // ????????
        return null;
    } else {
        // ?ID
        return movie.getId();
    }

}

From source file:com.mothsoft.alexis.dao.DocumentDaoImpl.java

License:Apache License

@Override
public ScrollableResults scrollableSearch(Long userId, DocumentState state, String queryString,
        SortOrder sortOrder, Date startDate, Date endDate) {
    final StopWatch stopWatch = new StopWatch();
    stopWatch.start();//from  w w  w  .  j a  v a2  s  .  c om

    final FullTextQuery fullTextQuery = this.buildFullTextQuery(queryString, userId, startDate, endDate, false,
            state, FullTextQuery.THIS, FullTextQuery.SCORE);

    final Sort sort;
    switch (sortOrder) {
    case DATE_ASC:
        sort = new Sort(new SortField("id", SortField.LONG));
        break;
    case DATE_DESC:
        sort = new Sort(new SortField("id", SortField.LONG, true));
        break;
    case RELEVANCE:
        sort = new Sort(SortField.FIELD_SCORE, new SortField("id", SortField.LONG, true));
        break;
    default:
        throw new IllegalArgumentException("Unexpected SortOrder: " + sortOrder.name());
    }
    fullTextQuery.setSort(sort);

    fullTextQuery.setFetchSize(50);
    fullTextQuery.setReadOnly(true);
    fullTextQuery.setCacheable(false);
    fullTextQuery.setCacheMode(CacheMode.IGNORE);

    final ScrollableResults result = fullTextQuery.scroll(ScrollMode.FORWARD_ONLY);

    stopWatch.stop();
    logger.debug(stopWatch.toString());

    return result;
}

From source file:com.mysema.query.jpa.HibernateHandler.java

License:Apache License

@Override
public <T> CloseableIterator<T> iterate(Query query, FactoryExpression<?> projection) {
    if (query instanceof HibernateQuery) {
        HibernateQuery hQuery = (HibernateQuery) query;
        ScrollableResults results = hQuery.getHibernateQuery().scroll(ScrollMode.FORWARD_ONLY);
        CloseableIterator<T> iterator = new ScrollableResultsIterator<T>(results);
        if (projection != null) {
            iterator = new TransformingIterator<T>(iterator, projection);
        }/*from  w  ww . jav a  2s . c  o  m*/
        return iterator;
    } else {
        Iterator<T> iterator = query.getResultList().iterator();
        if (projection != null) {
            return new TransformingIterator<T>(iterator, projection);
        } else {
            return new IteratorAdapter<T>(iterator);
        }
    }
}

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

License:Open Source License

/**
 * FlushToIndexes implementation//  w  w  w.  j  av  a 2s . c o  m
 */
@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;

    // 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);
        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, nodeType, 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 {
        Config.SYSTEM_READONLY = false;
        Config.SYSTEM_MAINTENANCE = false;
        HibernateUtil.close(ftSession);
        HibernateUtil.close(session);
    }

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

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

From source file:com.querydsl.jpa.hibernate.AbstractHibernateQuery.java

License:Apache License

/**
 * Return the query results as an <tt>Iterator</tt>. If the query
 * contains multiple results pre row, the results are returned in
 * an instance of <tt>Object[]</tt>.<br>
 * <br>/*w w  w  .  j a v  a 2 s  .  co  m*/
 * Entities returned as results are initialized on demand. The first
 * SQL query returns identifiers only.<br>
 */
@Override
public CloseableIterator<T> iterate() {
    try {
        Query query = createQuery();
        ScrollableResults results = query.scroll(ScrollMode.FORWARD_ONLY);
        return new ScrollableResultsIterator<T>(results);
    } finally {
        reset();
    }
}

From source file:com.querydsl.jpa.hibernate.sql.AbstractHibernateSQLQuery.java

License:Apache License

@Override
public CloseableIterator<T> iterate() {
    try {// w w w.  java  2s.  c om
        Query query = createQuery();
        ScrollableResults results = query.scroll(ScrollMode.FORWARD_ONLY);
        return new ScrollableResultsIterator<T>(results);
    } finally {
        reset();
    }
}