Example usage for org.hibernate Query scroll

List of usage examples for org.hibernate Query scroll

Introduction

In this page you can find the example usage for org.hibernate Query scroll.

Prototype

ScrollableResults scroll();

Source Link

Document

Return the query results as ScrollableResults.

Usage

From source file:no.magott.spring.FetchJoinTests.java

License:Apache License

private int getCountFromScrollableResults(Query query) {
    ScrollableResults scrollableResults = query.scroll();
    int count;/*from   ww w .j  a va  2s . c o m*/
    for (count = 0; scrollableResults.next(); count++) {
    }
    return count;
}

From source file:org.codehaus.grepo.query.hibernate.executor.ScrollQueryExecutor.java

License:Apache License

/**
 * {@inheritDoc}//w  w w  . j a  v  a 2  s.c  o m
 */
public Object execute(QueryMethodParameterInfo qmpi, HibernateQueryExecutionContext context) {
    HibernateQueryOptions queryOptions = qmpi.getMethodAnnotation(HibernateQueryOptions.class);
    ScrollMode scrollMode = getScrollMode(qmpi, queryOptions);

    Criteria criteria = createCriteria(qmpi, context);
    if (criteria == null) {
        Query query = createQuery(qmpi, context);
        if (scrollMode == null) {
            return query.scroll();
        }
        return query.scroll(scrollMode);
    }
    if (scrollMode == null) {
        return criteria.scroll();
    }
    return criteria.scroll(scrollMode);
}

From source file:org.esupportail.commons.dao.AbstractHibernateQueryPaginator.java

License:Apache License

/**
 * @see org.esupportail.commons.web.beans.AbstractPaginator#loadItemsInternal()
 *//*from  w  w w . j  a v a  2s  .  co  m*/
@Override
@SuppressWarnings("unchecked")
protected void loadItemsInternal() {
    String queryString = getQueryString();
    if (queryString == null) {
        setVisibleItems(new ArrayList<E>());
        setCurrentPageInternal(0);
        setTotalItemsCount(0);
        return;
    }
    Query query = getDaoService().getQuery(queryString);
    ScrollableResults scrollableResults = query.scroll();
    /* 
     * We set the max results to one more than the specfied pageSize to 
     * determine if any more results exist (i.e. if there is a next page 
     * to display). The result set is trimmed down to just the pageSize 
     * before being displayed later (in getList()). 
     */
    if (logger.isDebugEnabled()) {
        logger.debug("executing " + query.getQueryString() + "...");
    }
    query.setFirstResult(getCurrentPageInternal() * getPageSize());
    query.setMaxResults(getPageSize());
    setVisibleItems(query.list());
    // the total number of results is computed here since scrolling is not allowed when rendering
    scrollableResults.last();
    setTotalItemsCount(scrollableResults.getRowNumber() + 1);
    if (logger.isDebugEnabled()) {
        logger.debug("done.");
    }
    if (getVisibleItemsCountInternal() == 0 && getTotalItemsCountInternal() != 0) {
        setCurrentPageInternal(getLastPageNumberInternal());
        loadItemsInternal();
    }
    updateLoadTime();
}

From source file:org.glite.security.voms.admin.persistence.dao.VOMSUserDAO.java

License:Apache License

public ScrollableResults findAllWithCursor() {

    Query q = HibernateFactory.getSession().createQuery("select u from VOMSUser u order by u.surname asc");

    q.setCacheMode(CacheMode.IGNORE).scroll(ScrollMode.FORWARD_ONLY);

    return q.scroll();

}

From source file:org.mifos.framework.hibernate.helper.QueryResultDTOImpl.java

License:Open Source License

/**
 * Set the query which will be used for query execution
 *
 *///from   ww w.j  av a2  s . c o m
@Override
public void executeQuery(Query query) throws HibernateSearchException {
    if (query == null) {
        throw new HibernateSearchException(HibernateConstants.SEARCH_INPUTNULL);
    }
    try {
        scrollResult = query.scroll();
    } catch (HibernateException h) {
        throw new HibernateSearchException(HibernateConstants.SEARCH_FAILED, h);
    }

}

From source file:org.olat.course.statistic.export.SQLLogExporter.java

License:Apache License

/**
 * @TODO: charSet is currently ignored!!!!!
 * @see org.olat.course.statistic.export.ICourseLogExporter#exportCourseLog(java.io.File, java.lang.String, java.lang.Long, java.util.Date, java.util.Date, boolean)
 */// www .j a v  a2  s . c o  m
@Override
public void exportCourseLog(final File outFile, final String charSet, final Long resourceableId,
        final Date begin, Date end, final boolean resourceAdminAction, final boolean anonymize) {
    log_.info("exportCourseLog: BEGIN outFile=" + outFile + ", charSet=" + charSet + ", resourceableId="
            + resourceableId + ", begin=" + begin + ", end=" + end + ", resourceAdminAction="
            + resourceAdminAction + ", anonymize=" + anonymize);
    try {
        if (!outFile.exists()) {
            if (!outFile.getParentFile().exists() && !outFile.getParentFile().mkdirs()) {
                throw new IllegalArgumentException(
                        "Cannot create parent of OutFile " + outFile.getAbsolutePath());
            }
            if (!outFile.createNewFile()) {
                throw new IllegalArgumentException("Cannot create outFile " + outFile.getAbsolutePath());
            }
        }
    } catch (final IOException e) {
        e.printStackTrace();
        throw new IllegalArgumentException("Cannot create outFile " + outFile.getAbsolutePath());
    }
    if (!outFile.delete()) {
        throw new IllegalStateException("Could not delete temporary outfile " + outFile.getAbsolutePath());
    }

    // try to make sure the database can write into this directory
    if (!outFile.getParentFile().setWritable(true, false)) {
        log_.warn("exportCourseLog: COULD NOT SET DIR TO WRITEABLE: " + outFile.getParent());
    }

    String query = String.valueOf(anonymize ? anonymizedUserSql_ : nonAnonymizedUserSql_);
    if (begin != null) {
        query = query.concat(" AND (v.creationDate >= :createdAfter)");
    }
    if (end != null) {
        query = query.concat(" AND (v.creationDate <= :createdBefore)");
    }

    final Session session = sessionFactory_.openSession();
    final long startTime = System.currentTimeMillis();
    try {
        session.beginTransaction();
        final Query dbQuery = session.createSQLQuery(query);

        dbQuery.setBoolean("resAdminAction", resourceAdminAction);
        dbQuery.setString("resId", Long.toString(resourceableId));
        if (begin != null) {
            dbQuery.setDate("createdAfter", begin);
        }
        if (end != null) {
            final Calendar cal = Calendar.getInstance();
            cal.setTime(end);
            cal.add(Calendar.DAY_OF_MONTH, 1);
            end = cal.getTime();
            dbQuery.setDate("createdBefore", end);
        }

        dbQuery.setString("outFile", outFile.getAbsolutePath());

        dbQuery.scroll();
    } catch (final RuntimeException e) {
        e.printStackTrace(System.out);
    } catch (final Error er) {
        er.printStackTrace(System.out);
    } finally {
        if (session != null) {
            session.close();
        }
        final long diff = System.currentTimeMillis() - startTime;
        log_.info("exportCourseLog: END DURATION=" + diff + ", outFile=" + outFile + ", charSet=" + charSet
                + ", resourceableId=" + resourceableId + ", begin=" + begin + ", end=" + end
                + ", resourceAdminAction=" + resourceAdminAction + ", anonymize=" + anonymize);
    }
}

From source file:org.openbravo.costing.LandedCostDistributionByAmount.java

License:Open Source License

private ScrollableResults getReceiptCosts(LandedCost landedCost, boolean doOrderBy) {
    StringBuffer qry = new StringBuffer();
    qry.append("select lcr.id as lcreceipt"); // 0
    qry.append("   , iol.id as receiptline"); // 1
    qry.append("   , trx." + MaterialTransaction.PROPERTY_CURRENCY + ".id as currency"); // 2
    qry.append("   , sum(tc." + TransactionCost.PROPERTY_COST + ") as cost"); // 3
    qry.append(" from " + TransactionCost.ENTITY_NAME + " as tc");
    qry.append("   join tc." + TransactionCost.PROPERTY_INVENTORYTRANSACTION + " as trx");
    qry.append("   join trx." + MaterialTransaction.PROPERTY_GOODSSHIPMENTLINE + " as iol");
    qry.append(" , " + LCReceipt.ENTITY_NAME + " as lcr");
    qry.append(" where tc." + CostAdjustmentLine.PROPERTY_UNITCOST + " = true");
    qry.append(" and iol." + ShipmentInOutLine.PROPERTY_MOVEMENTQUANTITY + " >= 0");
    qry.append("   and ((lcr." + LCReceipt.PROPERTY_GOODSSHIPMENTLINE + " is not null");
    qry.append("        and lcr." + LCReceipt.PROPERTY_GOODSSHIPMENTLINE + " = iol)");
    qry.append("         or (lcr." + LCReceipt.PROPERTY_GOODSSHIPMENTLINE + " is null");
    qry.append("        and lcr." + LCReceipt.PROPERTY_GOODSSHIPMENT + " = iol."
            + ShipmentInOutLine.PROPERTY_SHIPMENTRECEIPT + "))");
    qry.append("   and lcr." + LCReceipt.PROPERTY_LANDEDCOST + ".id = :landedCost");
    qry.append(" group by lcr.id, iol.id, trx." + MaterialTransaction.PROPERTY_CURRENCY + ".id, iol."
            + ShipmentInOutLine.PROPERTY_LINENO);
    if (doOrderBy) {
        qry.append(" order by iol." + ShipmentInOutLine.PROPERTY_LINENO);
        qry.append(" , sum(tc." + TransactionCost.PROPERTY_COST + ")");
    }// w  ww .  j a  v a  2 s.  c o m

    Query qryReceiptCosts = OBDal.getInstance().getSession().createQuery(qry.toString());
    qryReceiptCosts.setParameter("landedCost", landedCost.getId());

    return qryReceiptCosts.scroll();
}

From source file:org.openbravo.service.datasource.HQLDataSourceService.java

License:Open Source License

protected int getGroupedCount(Query countQuery) {
    int nRows = -1;
    ScrollableResults scrollableResults = countQuery.scroll();
    if (scrollableResults.last()) {
        nRows = scrollableResults.getRowNumber();
    }/*www . ja va2s  .com*/
    scrollableResults.close();
    return nRows + 1;
}

From source file:org.riotfamily.common.hibernate.ActiveRecord.java

License:Apache License

/**
 * Convenience method to perform some code for every single result obtained
 * by the given query. It's save to call this method on a result set of
 * arbitrary length./*from  w w w  . j ava 2  s. c om*/
 * <p>
 * This is achieved by two design decisions: {@link Query#scroll()}
 * is used to obtain a scrollable result set and after processing a single
 * result, {@link Session#evict(Object)} is called for the entity just
 * processed. So, implementors of {@link ForEachCallback} must be aware
 * that only the currently processed entity is attached to the
 * Hibernate {@link Session}.
 * 
 * @param <T> a mapped type or {@link Object[]} if the query returns more
 *        than 1 column per row
 * @param query the Query to execute
 * @param callback a {@link ForEachCallback} to call for every entity
 *        returned by the given query
 * 
 * @see Query#scroll()
 * @see Session#evict(Object)
 * @see ForEachCallback
 */
@SuppressWarnings("unchecked")
protected static <T> void forEach(Query query, ForEachCallback<T> callback) {
    ScrollableResults results = query.scroll();
    while (results.next()) {
        Object[] row = results.get();
        callback.execute(row.length > 1 ? (T) row : (T) row[0]);
        for (Object entity : row) {
            getSession().evict(entity);
        }
    }
}

From source file:org.sakaiproject.tool.assessment.facade.util.PagingUtilQueries.java

License:Educational Community License

public List getAll(final int pageSize, final int pageNumber, final String queryString, final Integer value) {

    HibernateCallback callback = new HibernateCallback() {
        public Object doInHibernate(Session session) throws HibernateException {
            ArrayList page = new ArrayList();
            Query q = session.createQuery(queryString);
            if (value != null) {
                q.setInteger(0, value.intValue());
            }/*from  w  w  w. j  a  v a2 s .  c  om*/
            ScrollableResults assessmentList = q.scroll();
            if (assessmentList.first()) { // check that result set is not empty
                int first = pageSize * (pageNumber - 1);
                int i = 0;
                assessmentList.setRowNumber(first);
                assessmentList.beforeFirst();
                while ((pageSize > i++) && assessmentList.next()) {
                    log.debug("**** add " + i);
                    page.add(assessmentList.get(0));
                }
            }
            return page;
        }
    };
    List pageList = (List) getHibernateTemplate().execute(callback);
    return pageList;
}