Example usage for org.hibernate ScrollableResults first

List of usage examples for org.hibernate ScrollableResults first

Introduction

In this page you can find the example usage for org.hibernate ScrollableResults first.

Prototype

boolean first();

Source Link

Document

Go to the first result.

Usage

From source file:com.ikon.module.db.stuff.IndexHelper.java

License:Open Source License

protected int doRebuildIndex() throws Exception {
    FullTextSession fullTextSession = (FullTextSession) entityManager.getDelegate();
    fullTextSession.setFlushMode(org.hibernate.FlushMode.MANUAL);
    fullTextSession.setCacheMode(org.hibernate.CacheMode.IGNORE);
    fullTextSession.purgeAll(NodeDocumentVersion.class);
    fullTextSession.getSearchFactory().optimize(NodeDocumentVersion.class);

    String query = "select ndv from NodeDocumentVersion ndv";
    ScrollableResults cursor = fullTextSession.createQuery(query).scroll();
    cursor.last();//from  w  ww.  j  a va 2 s  .  c om
    int count = cursor.getRowNumber() + 1;
    log.warn("Re-building Wine index for " + count + " objects.");

    if (count > 0) {
        int batchSize = 300;
        cursor.first(); // Reset to first result row
        int i = 0;

        while (true) {
            fullTextSession.index(cursor.get(0));

            if (++i % batchSize == 0) {
                fullTextSession.flushToIndexes();
                fullTextSession.clear(); // Clear persistence context for each batch
                log.info("Flushed index update " + i + " from Thread " + Thread.currentThread().getName());
            }

            if (cursor.isLast()) {
                break;
            }

            cursor.next();
        }
    }

    cursor.close();
    fullTextSession.flushToIndexes();
    fullTextSession.clear(); // Clear persistence context for each batch
    fullTextSession.getSearchFactory().optimize(NodeDocumentVersion.class);

    return count;
}

From source file:com.liferay.jbpm.util.QueryUtil.java

License:Open Source License

public static List<?> list(Query query, Dialect dialect, int begin, int end) {

    if ((begin == ALL_POS) && (end == ALL_POS)) {
        return query.list();
    } else {/*from  w  ww.ja  va 2s.  co  m*/
        if (dialect.supportsLimit()) {
            query.setMaxResults(end - begin);
            query.setFirstResult(begin);

            return query.list();
        } else {
            List<Object> list = new ArrayList<Object>();

            ScrollableResults sr = query.scroll();

            if (sr.first() && sr.scroll(begin)) {
                for (int i = begin; i < end; i++) {
                    Object obj = sr.get(0);

                    list.add(obj);

                    if (!sr.next()) {
                        break;
                    }
                }
            }

            return list;
        }
    }
}

From source file:com.liferay.jbpm.util.QueryUtil.java

License:Open Source License

public static List<?> randomList(Query query, Dialect dialect, int total, int num) {

    if ((total == 0) || (num == 0)) {
        return new ArrayList<Object>();
    }//from w  w w  . ja va 2 s . c  o  m

    if (num >= total) {
        return list(query, dialect, ALL_POS, ALL_POS);
    }

    int[] scrollIds = Randomizer.getInstance().nextInt(total, num);

    List<Object> list = new ArrayList<Object>();

    ScrollableResults sr = query.scroll();

    for (int i = 0; i < scrollIds.length; i++) {
        if (sr.scroll(scrollIds[i])) {
            Object obj = sr.get(0);

            list.add(obj);

            sr.first();
        }
    }

    return list;
}

From source file:com.liferay.jbpm.util.QueryUtil.java

License:Open Source License

public static Comparable<?>[] getPrevAndNext(Query query, int count, OrderByComparator obc,
        Comparable<?> comparable) {

    int pos = count;
    int boundary = 0;

    Comparable<?>[] array = new Comparable[3];

    ScrollableResults sr = query.scroll();

    if (sr.first()) {
        while (true) {
            Object obj = sr.get(0);

            if (obj == null) {
                if (_log.isWarnEnabled()) {
                    _log.warn("Object is null");
                }/*from w  ww  .  j  av  a2s  . co m*/

                break;
            }

            Comparable<?> curComparable = (Comparable<?>) obj;

            int value = obc.compare(comparable, curComparable);

            if (_log.isDebugEnabled()) {
                _log.debug("Comparison result is " + value);
            }

            if (value == 0) {
                if (!comparable.equals(curComparable)) {
                    break;
                }

                array[1] = curComparable;

                if (sr.previous()) {
                    array[0] = (Comparable<?>) sr.get(0);
                }

                sr.next();

                if (sr.next()) {
                    array[2] = (Comparable<?>) sr.get(0);
                }

                break;
            }

            if (pos == 1) {
                break;
            }

            pos = (int) Math.ceil(pos / 2.0);

            int scrollPos = pos;

            if (value < 0) {
                scrollPos = scrollPos * -1;
            }

            boundary += scrollPos;

            if (boundary < 0) {
                scrollPos = scrollPos + (boundary * -1) + 1;

                boundary = 0;
            }

            if (boundary > count) {
                scrollPos = scrollPos - (boundary - count);

                boundary = scrollPos;
            }

            if (_log.isDebugEnabled()) {
                _log.debug("Scroll " + scrollPos);
            }

            if (!sr.scroll(scrollPos)) {
                if (value < 0) {
                    if (!sr.next()) {
                        break;
                    }
                } else {
                    if (!sr.previous()) {
                        break;
                    }
                }
            }
        }
    }

    return array;
}

From source file:com.multimedia.service.wallpaper.WallpaperServiceImpl.java

License:Apache License

@Override
public Map<String, Double> getTags(int maxTags) {
    ScrollableResults wallpaper_tags = dao.getScrollableResults("tags", "active", Boolean.TRUE, null, null);
    Map<String, Double> tags = new HashMap<String, Double>();
    if (wallpaper_tags.first()) {
        String tag;/*from   w  w  w  .  j a v  a2  s . c  o m*/
        Double score;
        String[] tags_parsed;
        String tag_parsed;
        do {
            tag = wallpaper_tags.getString(0);
            if (tag != null) {
                tags_parsed = tag.split(",");
                for (int i = 1; i < tags_parsed.length; i++) {
                    tag_parsed = tags_parsed[i].trim();
                    if (!black_word_list.contains(tag_parsed)) {
                        score = tags.get(tag_parsed);
                        if (score == null) {
                            tags.put(tag_parsed, new Double(1.0));
                        } else {
                            tags.put(tag_parsed, (score + 1));
                        }
                    }
                }
            }
        } while (wallpaper_tags.next());
    }
    wallpaper_tags.close();
    //keeping only maxTags quantity
    Set<Entry<String, Double>> i = tags.entrySet();
    List<Entry<String, Double>> l = new LinkedList<Entry<String, Double>>(i);
    java.util.Collections.sort(l, new WallpaperServiceImpl.EntryComparatorDesc());

    if (maxTags > 0) {
        for (int j = maxTags; j < l.size(); j++) {
            tags.remove(l.get(j).getKey());
        }
    }
    return tags;
}

From source file:net.chrisrichardson.foodToGo.domain.hibernate.HibernateOrderRepositoryImpl.java

License:Apache License

private List getOrdersFromScrollableResults(ScrollableResults results1) {
    List orders = new ArrayList();
    int pageSize = 10;
    if (results1.first() && results1.scroll(0)) {
        for (int i = 0; i < pageSize; i++) {
            orders.add(results1.get(0));
            if (!results1.next())
                break;
        }/*from   w ww  .  j  av a2 s .c  o m*/
    }

    List results = orders;
    return results;
}

From source file:net.mlw.vlh.adapter.hibernate3.HibernateAdapter.java

License:Open Source License

/**
 * @see net.mlw.vlh.ValueListAdapter#getValueList(java.lang.String,
 *      net.mlw.vlh.ValueListInfo)//from  w w  w .j  av  a2  s .co m
 */
public ValueList getValueList(String name, ValueListInfo info) {

    LOGGER.debug("getValueList(String, ValueListInfo) - start");

    if (info.getSortingColumn() == null) {
        info.setPrimarySortColumn(getDefaultSortColumn());
        info.setPrimarySortDirection(getDefaultSortDirectionInteger());
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("The default sort column '" + getDefaultSortColumn() + "' with direction '"
                    + getDefaultSortDirectionInteger() + "' was  set.");
        }
    }

    int numberPerPage = info.getPagingNumberPer();

    if (numberPerPage == Integer.MAX_VALUE) {
        numberPerPage = getDefaultNumberPerPage();
        info.setPagingNumberPer(numberPerPage);
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("The paging number per page '" + numberPerPage + "' was  set.");
        }
    }

    Session session = SessionFactoryUtils.getSession(getSessionFactory(), allowCreate);
    try {
        Query query;

        boolean doFocus = ((getAdapterType() & DO_FOCUS) == 0) && info.isFocusEnabled() && info.isDoFocus()
                && (namedQuery == null);

        if (doFocus) {
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug(
                        "Start to focusing adapterName '" + name + "', ValueListInfo info = " + info + "'");
            }
            ScrollableResults results = getScrollableResults(getQueryForFocus(info, session), info);
            results.beforeFirst();
            doFocusFor(info, results);

            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug(
                        "Focusing finished for adapterName '" + name + "', ValueListInfo info '" + info + "'");
            }
        }

        query = getQuery(info, session);

        boolean doPaging = ((getAdapterType() & DO_PAGE) == 0);

        List list;

        if (doPaging) {
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("getValueList(String adapterName = " + name + ", ValueListInfo info = " + info
                        + ") - Start to paging result set");
            }

            list = new ArrayList(numberPerPage);
            ScrollableResults results = getScrollableResults(query, info);

            results.last();
            int lastRowNumber = results.getRowNumber();
            info.setTotalNumberOfEntries(lastRowNumber + 1);

            if (numberPerPage == 0) {
                numberPerPage = getDefaultNumberPerPage();
            }

            int pageNumber = info.getPagingPage();
            boolean isResult;
            if (pageNumber > 1) {
                if ((pageNumber - 1) * numberPerPage > lastRowNumber) {
                    pageNumber = (lastRowNumber / numberPerPage) + 1;
                    info.setPagingPage(pageNumber);
                }
            }
            // fixed by liujuan 2008.6.5
            isResult = results.first();

            if (pageNumber > 1) {
                // isResult = results.scroll((pageNumber - 1) * numberPerPage - lastRowNumber);
                isResult = results.scroll((pageNumber - 1) * numberPerPage);
            }
            /*else
            {
               isResult = results.first();
            }*/

            for (int i = 0; i < numberPerPage && isResult; i++) {
                list.add(results.get(0));
                isResult = results.next();
            }

            LOGGER.debug("Sorting finished.");

        } else {

            LOGGER.debug("Retrieving a list directly from the query.");

            list = query.list();
            info.setTotalNumberOfEntries(list.size());
        }

        ValueList returnValueList = getListBackedValueList(info, list);
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Retrieved list was wrapped in valuelist, info=" + info);
        }
        return returnValueList;
    } catch (HibernateException e) {
        LOGGER.error("Error getting data in adapater '" + name + "' with info = '" + info + "'", e);
        throw SessionFactoryUtils.convertHibernateAccessException(e);
    } catch (Exception e) {
        LOGGER.fatal("Fatal error getting data in adapater '" + name + "' with info = '" + info + "'", e);
        return null;
    } finally {
        SessionFactoryUtils.releaseSession(session, getSessionFactory());
    }
}

From source file:org.gbif.portal.dao.DAOUtils.java

License:Open Source License

/**
 * Process results, scrolling through each record in turn only loading that specific record.
 * // w  ww  . j a  v  a2 s.c o m
 * @param resultsOutputter
 * @param session
 * @param query
 * @param associationTraverser
 * @param batchSize
 * @throws IOException
 */
public static void scrollResults(final ResultsOutputter resultsOutputter, Session session, Query query,
        AssociationTraverser associationTraverser, int batchSize) throws IOException {
    query.setReadOnly(true);
    query.setFetchSize(batchSize);

    //Using scrollable results to prevent initiation of all model objects
    ScrollableResults sr = query.scroll(ScrollMode.FORWARD_ONLY);

    //go to beginning of resultset
    boolean isNotEmpty = sr.first();
    if (!isNotEmpty) {
        //this is necessary due to a bug with ScrollableResults
        //allowing continuous scrolling over an empty resultset. genius.
        return;
    }

    //iterate through the results
    processScrollableResults(resultsOutputter, session, sr, associationTraverser, batchSize);

    //check for a chain
    if (resultsOutputter instanceof ChainableResultsOutputter) {
        ChainableResultsOutputter cro = (ChainableResultsOutputter) resultsOutputter;
        ResultsOutputter nextResultsOutputter = cro.getNextResultsOutputter();
        while (nextResultsOutputter != null && !cro.isChainInOnePass()) {
            //back to the start
            sr.first();
            processScrollableResults(nextResultsOutputter, session, sr, associationTraverser, batchSize);
            if (resultsOutputter instanceof ChainableResultsOutputter) {
                cro = (ChainableResultsOutputter) resultsOutputter;
                if (!cro.isChainInOnePass())
                    nextResultsOutputter = cro.getNextResultsOutputter();
                else
                    nextResultsOutputter = null;
            } else {
                nextResultsOutputter = null;
            }
        }
    }
    if (associationTraverser != null)
        associationTraverser.reset();
    //close the results set
    sr.close();
}

From source file:org.opentaps.common.domain.order.PurchaseOrderLookupRepository.java

License:Open Source License

/** {@inheritDoc} */
public List<OrderViewForListing> findOrders() throws RepositoryException {

    // convert fromDateStr / thruDateStr into Timestamps if the string versions were given
    if (UtilValidate.isNotEmpty(fromDateStr)) {
        fromDate = UtilDate.toTimestamp(fromDateStr, timeZone, locale);
    }//  w  w  w. j  a v a 2s.c o m
    if (UtilValidate.isNotEmpty(thruDateStr)) {
        thruDate = UtilDate.toTimestamp(thruDateStr, timeZone, locale);
    }
    Session session = null;
    try {
        // get a hibernate session
        session = getInfrastructure().getSession();
        Criteria criteria = session.createCriteria(OrderHeader.class);

        // always filter by the current organization
        criteria.add(Restrictions.eq(OrderHeader.Fields.billToPartyId.name(), organizationPartyId));

        // filters by order type, we only want purchase order
        criteria.add(Restrictions.eq(OrderHeader.Fields.orderTypeId.name(), OrderTypeConstants.PURCHASE_ORDER));

        // set the from/thru date filter if they were given
        if (fromDate != null) {
            criteria.add(Restrictions.ge(OrderHeader.Fields.orderDate.name(), fromDate));
        }
        if (thruDate != null) {
            criteria.add(Restrictions.le(OrderHeader.Fields.orderDate.name(), thruDate));
        }

        // filter the role assoc, there is only one supplier role per order
        Criteria roleCriteria = criteria.createAlias("orderRoles", "or");
        roleCriteria.add(Restrictions.eq("or.id." + OrderRole.Fields.roleTypeId.name(),
                RoleTypeConstants.BILL_FROM_VENDOR));

        // filter by order status
        if (findDesiredOnly) {
            List<String> statuses = UtilMisc.toList(StatusItemConstants.OrderStatus.ORDER_APPROVED,
                    StatusItemConstants.OrderStatus.ORDER_CREATED, StatusItemConstants.OrderStatus.ORDER_HOLD);
            criteria.add(Restrictions.in(OrderHeader.Fields.statusId.name(), statuses));
        }

        // filter by the given orderId string
        if (UtilValidate.isNotEmpty(orderId)) {
            criteria.add(Restrictions.ilike(OrderHeader.Fields.orderId.name(), orderId, MatchMode.START));
        }

        // filter by exact matching status, if a statusId was given
        if (UtilValidate.isNotEmpty(statusId)) {
            criteria.add(Restrictions.eq(OrderHeader.Fields.statusId.name(), statusId));
        }

        // filter by the user who created the order if given
        if (UtilValidate.isNotEmpty(createdBy)) {
            criteria.add(Restrictions.eq(OrderHeader.Fields.createdBy.name(), createdBy));
        }

        // filter by the given orderName string
        if (UtilValidate.isNotEmpty(orderName)) {
            criteria.add(Restrictions.ilike(OrderHeader.Fields.orderName.name(), orderName, MatchMode.START));
        }

        // filter by the given supplierPartyId string, from the OrderRole entity
        if (UtilValidate.isNotEmpty(supplierPartyId)) {
            roleCriteria.add(Restrictions.ilike("or.id." + OrderRole.Fields.partyId.name(), supplierPartyId,
                    MatchMode.START));
        }

        // filter by product, if given
        criteria.createAlias("orderItems", "oi");
        if (UtilValidate.isNotEmpty(productPattern)) {
            try {
                // try to get product by using productPattern as productId
                Product product = getProductRepository().getProductById(productPattern);
                criteria.add(
                        Restrictions.eq("oi." + OrderItem.Fields.productId.name(), product.getProductId()));
            } catch (EntityNotFoundException e) {
                // could not get the product by using productPattern as productId
                // find all the products that may match
                String likePattern = "%" + productPattern + "%";
                EntityCondition conditionList = EntityCondition.makeCondition(EntityOperator.OR,
                        EntityCondition.makeCondition(ProductAndGoodIdentification.Fields.productId.getName(),
                                EntityOperator.LIKE, likePattern),
                        EntityCondition.makeCondition(
                                ProductAndGoodIdentification.Fields.internalName.getName(), EntityOperator.LIKE,
                                likePattern),
                        EntityCondition.makeCondition(ProductAndGoodIdentification.Fields.productName.getName(),
                                EntityOperator.LIKE, likePattern),
                        EntityCondition.makeCondition(ProductAndGoodIdentification.Fields.comments.getName(),
                                EntityOperator.LIKE, likePattern),
                        EntityCondition.makeCondition(ProductAndGoodIdentification.Fields.description.getName(),
                                EntityOperator.LIKE, likePattern),
                        EntityCondition.makeCondition(
                                ProductAndGoodIdentification.Fields.longDescription.getName(),
                                EntityOperator.LIKE, likePattern),
                        EntityCondition.makeCondition(ProductAndGoodIdentification.Fields.idValue.getName(),
                                EntityOperator.LIKE, likePattern));
                List<ProductAndGoodIdentification> products = findList(ProductAndGoodIdentification.class,
                        conditionList);
                if (products.size() > 0) {
                    criteria.add(Restrictions.in("oi." + OrderItem.Fields.productId.name(), Entity
                            .getDistinctFieldValues(products, ProductAndGoodIdentification.Fields.productId)));
                }
            }
        }

        // specify the fields to return
        criteria.setProjection(Projections.projectionList()
                .add(Projections.distinct(Projections.property(OrderHeader.Fields.orderId.name())))
                .add(Projections.property(OrderHeader.Fields.orderName.name()))
                .add(Projections.property(OrderHeader.Fields.statusId.name()))
                .add(Projections.property(OrderHeader.Fields.grandTotal.name()))
                .add(Projections.property(OrderHeader.Fields.orderDate.name()))
                .add(Projections.property(OrderHeader.Fields.currencyUom.name()))
                .add(Projections.property("or.id." + OrderRole.Fields.partyId.name())));

        // set the order by
        if (orderBy == null) {
            orderBy = Arrays.asList(OrderHeader.Fields.orderDate.desc());
        }
        // some substitution is needed to fit the hibernate field names
        // this also maps the calculated fields and indicates the non sortable fields
        Map<String, String> subs = new HashMap<String, String>();
        subs.put("partyId", "or.id.partyId");
        subs.put("partyName", "or.id.partyId");
        subs.put("orderDateString", "orderDate");
        subs.put("orderNameId", "orderId");
        subs.put("statusDescription", "statusId");
        HibernateUtil.setCriteriaOrder(criteria, orderBy, subs);

        ScrollableResults results = null;
        List<OrderViewForListing> results2 = new ArrayList<OrderViewForListing>();
        try {
            // fetch the paginated results
            results = criteria.scroll(ScrollMode.SCROLL_INSENSITIVE);
            if (usePagination()) {
                results.setRowNumber(getPageStart());
            } else {
                results.first();
            }

            // convert them into OrderViewForListing objects which will also calculate or format some fields for display
            Object[] o = results.get();
            int n = 0; // number of results actually read
            while (o != null) {
                OrderViewForListing r = new OrderViewForListing();
                r.initRepository(this);
                int i = 0;
                r.setOrderId((String) o[i++]);
                r.setOrderName((String) o[i++]);
                r.setStatusId((String) o[i++]);
                r.setGrandTotal((BigDecimal) o[i++]);
                r.setOrderDate((Timestamp) o[i++]);
                r.setCurrencyUom((String) o[i++]);
                r.setPartyId((String) o[i++]);
                r.calculateExtraFields(getDelegator(), timeZone, locale);
                results2.add(r);
                n++;

                if (!results.next()) {
                    break;
                }
                if (usePagination() && n >= getPageSize()) {
                    break;
                }
                o = results.get();
            }
            results.last();
            // note: row number starts at 0
            setResultSize(results.getRowNumber() + 1);
        } finally {
            results.close();
        }

        return results2;

    } catch (InfrastructureException e) {
        throw new RepositoryException(e);
    } finally {
        if (session != null) {
            session.close();
        }
    }
}

From source file:org.opentaps.common.domain.order.SalesOrderLookupRepository.java

License:Open Source License

/** {@inheritDoc} */
public List<OrderViewForListing> findOrders() throws RepositoryException {

    // convert fromDateStr / thruDateStr into Timestamps if the string versions were given
    if (UtilValidate.isNotEmpty(fromDateStr)) {
        fromDate = UtilDate.toTimestamp(fromDateStr, timeZone, locale);
    }//from  w w w .j a  v a2  s .c o m
    if (UtilValidate.isNotEmpty(thruDateStr)) {
        thruDate = UtilDate.toTimestamp(thruDateStr, timeZone, locale);
    }
    Session session = null;
    try {
        // get a hibernate session
        session = getInfrastructure().getSession();
        Criteria criteria = session.createCriteria(OrderHeader.class);

        // always filter by the current organization
        criteria.add(Restrictions.eq(OrderHeader.Fields.billFromPartyId.name(), organizationPartyId));

        // filters by order type, we only want sales order
        criteria.add(Restrictions.eq(OrderHeader.Fields.orderTypeId.name(), OrderTypeConstants.SALES_ORDER));

        // set the from/thru date filter if they were given
        if (fromDate != null) {
            criteria.add(Restrictions.ge(OrderHeader.Fields.orderDate.name(), fromDate));
        }
        if (thruDate != null) {
            criteria.add(Restrictions.le(OrderHeader.Fields.orderDate.name(), thruDate));
        }

        // filter the role assoc, there is only one customer role per order
        Criteria roleCriteria = criteria.createAlias("orderRoles", "or");
        roleCriteria.add(Restrictions.eq("or.id." + OrderRole.Fields.roleTypeId.name(),
                RoleTypeConstants.BILL_TO_CUSTOMER));

        // filter orders created by the given user (TODO: what use is viewPref as a string here, should be a boolean flag instead ?)
        if (UtilValidate.isNotEmpty(viewPref)) {
            criteria.add(Restrictions.eq(OrderHeader.Fields.createdBy.name(), userLoginId));
        }

        // filter by order status
        if (findActiveOnly || findDesiredOnly) {
            List<String> statuses = UtilMisc.toList(StatusItemConstants.OrderStatus.ORDER_APPROVED,
                    StatusItemConstants.OrderStatus.ORDER_CREATED, StatusItemConstants.OrderStatus.ORDER_HOLD);
            if (findActiveOnly) {
                statuses.add(StatusItemConstants.OrderStatus.ORDER_PROCESSING);
            }

            criteria.add(Restrictions.in(OrderHeader.Fields.statusId.name(), statuses));
        }

        // filter by the given orderId string
        if (UtilValidate.isNotEmpty(orderId)) {
            criteria.add(Restrictions.ilike(OrderHeader.Fields.orderId.name(), orderId, MatchMode.START));
        }
        // filter by the given externalOrderId string
        if (UtilValidate.isNotEmpty(externalOrderId)) {
            criteria.add(
                    Restrictions.ilike(OrderHeader.Fields.externalId.name(), externalOrderId, MatchMode.START));
        }

        // filter by exact matching status, if a statusId was given
        if (UtilValidate.isNotEmpty(statusId)) {
            criteria.add(Restrictions.eq(OrderHeader.Fields.statusId.name(), statusId));
        }

        // filter by product store if given
        if (UtilValidate.isNotEmpty(productStoreId)) {
            criteria.add(Restrictions.eq(OrderHeader.Fields.productStoreId.name(), productStoreId));
        }

        // filter by the user who created the order if given
        if (UtilValidate.isNotEmpty(createdBy)) {
            criteria.add(Restrictions.eq(OrderHeader.Fields.createdBy.name(), createdBy));
        }

        // filter by the given orderName string
        if (UtilValidate.isNotEmpty(orderName)) {
            criteria.add(Restrictions.ilike(OrderHeader.Fields.orderName.name(), orderName, MatchMode.START));
        }

        // filter by the given customerPartyId string, from the OrderRole entity
        if (UtilValidate.isNotEmpty(customerPartyId)) {
            roleCriteria.add(Restrictions.ilike("or.id." + OrderRole.Fields.partyId.name(), customerPartyId,
                    MatchMode.START));
        }

        // filter by the given purchaseOrderId string, from the OrderItem entity
        criteria.createAlias("orderItems", "oi");
        if (UtilValidate.isNotEmpty(purchaseOrderId)) {
            criteria.add(Restrictions.ilike("oi." + OrderItem.Fields.correspondingPoId.name(), purchaseOrderId,
                    MatchMode.START));
        }

        // filter by the given productId string, from the OrderItem entity
        if (UtilValidate.isNotEmpty(productId)) {
            criteria.add(
                    Restrictions.ilike("oi." + OrderItem.Fields.productId.name(), productId, MatchMode.START));
        }

        // filter by the given shippingAddress string, from the OrderItemShipGroup entity
        criteria.createAlias("orderItemShipGroups", "oisg");
        Criteria address = criteria.createCriteria("oisg.postalAddress");
        if (UtilValidate.isNotEmpty(shippingAddress)) {
            address.add(Restrictions.ilike(PostalAddress.Fields.address1.name(), shippingAddress,
                    MatchMode.ANYWHERE));
        }

        if (UtilValidate.isNotEmpty(shippingCountry)) {
            address.add(Restrictions.ilike(PostalAddress.Fields.countryGeoId.name(), shippingCountry,
                    MatchMode.EXACT));
        }

        if (UtilValidate.isNotEmpty(shippingStateProvince)) {
            address.add(Restrictions.ilike(PostalAddress.Fields.stateProvinceGeoId.name(),
                    shippingStateProvince, MatchMode.EXACT));
        }

        if (UtilValidate.isNotEmpty(shippingCity)) {
            address.add(Restrictions.ilike(PostalAddress.Fields.city.name(), shippingCity, MatchMode.START));
        }

        if (UtilValidate.isNotEmpty(shippingPostalCode)) {
            address.add(Restrictions.ilike(PostalAddress.Fields.postalCode.name(), shippingPostalCode,
                    MatchMode.START));
        }

        if (UtilValidate.isNotEmpty(shippingToName)) {
            address.add(
                    Restrictions.ilike(PostalAddress.Fields.toName.name(), shippingToName, MatchMode.START));
        }

        if (UtilValidate.isNotEmpty(shippingAttnName)) {
            address.add(Restrictions.ilike(PostalAddress.Fields.attnName.name(), shippingAttnName,
                    MatchMode.START));
        }
        // filter by the given lotId and serialNumber, which may come either from
        // OrderItemShipGrpInvRes -> InventoryItem
        // or
        // ItemIssuance -> InventoryItem
        criteria.createCriteria("orderItemShipGrpInvReses", Criteria.LEFT_JOIN).createCriteria("inventoryItem",
                "rii", Criteria.LEFT_JOIN);
        criteria.createCriteria("itemIssuances", Criteria.LEFT_JOIN).createCriteria("inventoryItem", "iii",
                Criteria.LEFT_JOIN);
        if (UtilValidate.isNotEmpty(lotId)) {
            criteria.add(Restrictions.or(
                    Restrictions.ilike("rii." + InventoryItem.Fields.lotId.name(), lotId, MatchMode.START),
                    Restrictions.ilike("iii." + InventoryItem.Fields.lotId.name(), lotId, MatchMode.START)));
        }
        if (UtilValidate.isNotEmpty(serialNumber)) {
            criteria.add(Restrictions.or(
                    Restrictions.ilike("rii." + InventoryItem.Fields.serialNumber.name(), serialNumber,
                            MatchMode.START),
                    Restrictions.ilike("iii." + InventoryItem.Fields.serialNumber.name(), serialNumber,
                            MatchMode.START)));
        }

        criteria.createCriteria("trackingCodeOrders", "tco", Criteria.LEFT_JOIN);

        // specify the fields to return
        criteria.setProjection(Projections.projectionList()
                .add(Projections.distinct(Projections.property(OrderHeader.Fields.orderId.name())))
                .add(Projections.property(OrderHeader.Fields.orderName.name()))
                .add(Projections.property(OrderHeader.Fields.statusId.name()))
                .add(Projections.property(OrderHeader.Fields.grandTotal.name()))
                .add(Projections.property(OrderHeader.Fields.orderDate.name()))
                .add(Projections.property(OrderHeader.Fields.currencyUom.name()))
                .add(Projections.property("or.id." + OrderRole.Fields.partyId.name()))
                .add(Projections.property("oi." + OrderItem.Fields.correspondingPoId.name()))
                .add(Projections.property("tco." + TrackingCodeOrder.Fields.trackingCodeId.name())));
        Debug.logInfo("criteria.toString() : " + criteria.toString(), MODULE);
        // set the order by
        if (orderBy == null) {
            orderBy = Arrays.asList(OrderHeader.Fields.orderDate.desc());
        }
        // some substitution is needed to fit the hibernate field names
        // this also maps the calculated fields and indicates the non sortable fields
        Map<String, String> subs = new HashMap<String, String>();
        subs.put("partyId", "or.id.partyId");
        subs.put("partyName", "or.id.partyId");
        subs.put("orderDateString", "orderDate");
        subs.put("shipByDateString", null);
        subs.put("orderNameId", "orderId");
        subs.put("statusDescription", "statusId");
        subs.put("correspondingPoId", "oi.correspondingPoId");
        subs.put("trackingCodeId", "tco.trackingCodeId");
        HibernateUtil.setCriteriaOrder(criteria, orderBy, subs);

        ScrollableResults results = null;
        List<OrderViewForListing> results2 = new ArrayList<OrderViewForListing>();
        try {
            // fetch the paginated results
            results = criteria.scroll(ScrollMode.SCROLL_INSENSITIVE);
            if (usePagination()) {
                results.setRowNumber(getPageStart());
            } else {
                results.first();
            }

            // convert them into OrderViewForListing objects which will also calculate or format some fields for display
            Object[] o = results.get();
            int n = 0; // number of results actually read
            while (o != null) {
                OrderViewForListing r = new OrderViewForListing();
                r.initRepository(this);
                int i = 0;
                r.setOrderId((String) o[i++]);
                r.setOrderName((String) o[i++]);
                r.setStatusId((String) o[i++]);
                r.setGrandTotal((BigDecimal) o[i++]);
                r.setOrderDate((Timestamp) o[i++]);
                r.setCurrencyUom((String) o[i++]);
                r.setPartyId((String) o[i++]);
                r.setCorrespondingPoId((String) o[i++]);
                r.setTrackingCodeId((String) o[i++]);
                r.calculateExtraFields(getDelegator(), timeZone, locale);
                results2.add(r);
                n++;

                if (!results.next()) {
                    break;
                }
                if (usePagination() && n >= getPageSize()) {
                    break;
                }
                o = results.get();
            }
            results.last();
            // note: row number starts at 0
            setResultSize(results.getRowNumber() + 1);
        } finally {
            if (results != null) {
                results.close();
            }
        }

        return results2;

    } catch (InfrastructureException e) {
        Debug.logError(e, MODULE);
        throw new RepositoryException(e);
    } finally {
        if (session != null) {
            session.close();
        }
    }
}