Example usage for org.hibernate ScrollableResults get

List of usage examples for org.hibernate ScrollableResults get

Introduction

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

Prototype

Object[] get();

Source Link

Document

Get the current row of results.

Usage

From source file:org.openhie.openempi.blocking.basicblockinghp.dao.hibernate.BlockingDaoHibernate.java

License:Open Source License

@SuppressWarnings({ "unchecked", "rawtypes" })
public void loadAllRecords(final Cache recordCache, final List<String> fieldNameSet) {
    final String[] fieldNames = fieldNameSet.toArray(new String[] {});
    //      final String queryStr = buildQuery(fieldNames).toString();
    getHibernateTemplate().execute(new HibernateCallback() {
        @Override/*from ww  w. j a  v  a 2 s . c  o m*/
        public Object doInHibernate(Session session) {
            try {
                org.hibernate.Criteria criteria = createQueryFromFields(session, fieldNameSet);
                criteria.setCacheMode(CacheMode.IGNORE);
                criteria.setFetchSize(10000);
                ScrollableResults iterator = criteria.scroll(ScrollMode.FORWARD_ONLY);
                //               Query query = session.createQuery(queryStr);
                //               query.setCacheMode(CacheMode.IGNORE);
                //               query.setFetchSize(10000);
                //               ScrollableResults iterator = query.scroll(ScrollMode.FORWARD_ONLY);
                int count = 0;
                while (iterator.next()) {
                    Object[] values = iterator.get();
                    Person person = populatePersonObject(fieldNames, values);
                    Record record = new Record(person);
                    Long recordId = person.getPersonId().longValue();
                    record.setRecordId(recordId);
                    Element element = new Element(recordId, record);
                    recordCache.put(element);
                    log.trace("Loaded record " + recordId + " into the cache.");
                    count++;
                }
                log.debug("Loaded " + count + " records into the cache.");
            } catch (Exception e) {
                log.error("Failed while scrolling through the records: " + e, e);
            }
            return null;
        }
    });
}

From source file:org.openmrs.module.amrsreports.db.hibernate.MohHibernateCoreDAO.java

License:Open Source License

@Override
public List<Object> executeScrollingHqlQuery(String query, Map<String, Object> substitutions) {
    Query q = sessionFactory.getCurrentSession().createQuery(query);

    applySubstitutions(q, substitutions);

    // optimizations go here
    q.setFetchSize(Integer.MIN_VALUE);
    q.setReadOnly(true);/*from w  ww.ja  v a2  s  .  co m*/

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

    long i = 0;

    ScrollableResults sr = q.scroll(ScrollMode.FORWARD_ONLY);
    while (sr.next()) {

        // rows always come back as an array
        Object[] o = sr.get();

        // but if there is only one object in the row, add it instead of the array
        if (o.length == 1)
            res.add(o[0]);
        else
            res.add(o);

        if (++i % 500 == 0)
            log.warn("processed #" + i);
    }

    log.warn("done. processed " + i + " total rows.");

    sr.close();

    return res;
}

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);
    }/*from   ww  w .  ja v  a  2 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.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);
    }//www  . j a va 2 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();
        }
    }
}

From source file:org.opentaps.financials.domain.billing.invoice.InvoiceLookupRepository.java

License:Open Source License

/** {@inheritDoc} */
public List<InvoiceViewForListing> findInvoices() throws RepositoryException {

    // convert from / thru from String into Timestamps if the string versions were given
    if (UtilValidate.isNotEmpty(fromInvoiceDateString)) {
        fromInvoiceDate = UtilDate.toTimestamp(fromInvoiceDateString, timeZone, locale);
    }//  w  w  w  .j  a va 2  s  . c o  m
    if (UtilValidate.isNotEmpty(thruInvoiceDateString)) {
        thruInvoiceDate = UtilDate.toTimestamp(thruInvoiceDateString, timeZone, locale);
    }
    if (UtilValidate.isNotEmpty(fromDueDateString)) {
        fromDueDate = UtilDate.toTimestamp(fromDueDateString, timeZone, locale);
    }
    if (UtilValidate.isNotEmpty(thruDueDateString)) {
        thruDueDate = UtilDate.toTimestamp(thruDueDateString, timeZone, locale);
    }
    if (UtilValidate.isNotEmpty(fromPaidDateString)) {
        fromPaidDate = UtilDate.toTimestamp(fromPaidDateString, timeZone, locale);
    }
    if (UtilValidate.isNotEmpty(thruPaidDateString)) {
        thruPaidDate = UtilDate.toTimestamp(thruPaidDateString, timeZone, locale);
    }
    Session session = null;
    try {
        // get a hibernate session
        session = getInfrastructure().getSession();
        Criteria criteria = session.createCriteria(Invoice.class);

        // always filter by invoice type
        criteria.add(Restrictions.eq(Invoice.Fields.invoiceTypeId.name(), invoiceTypeId));

        // some id filters
        if (UtilValidate.isNotEmpty(partyId)) {
            criteria.add(Restrictions.eq(Invoice.Fields.partyId.name(), partyId));
        }
        if (UtilValidate.isNotEmpty(partyIdFrom)) {
            criteria.add(Restrictions.eq(Invoice.Fields.partyIdFrom.name(), partyIdFrom));
        }
        if (UtilValidate.isNotEmpty(invoiceId)) {
            criteria.add(Restrictions.eq(Invoice.Fields.invoiceId.name(), invoiceId));
        }
        if (UtilValidate.isNotEmpty(statusId)) {
            criteria.add(Restrictions.eq(Invoice.Fields.statusId.name(), statusId));
        }
        if (UtilValidate.isNotEmpty(processingStatusId)) {
            // this is a special case where we want an empty status
            if ("_NA_".equals(processingStatusId)) {
                criteria.add(Restrictions.eq(Invoice.Fields.processingStatusId.name(), null));
            } else {
                criteria.add(Restrictions.eq(Invoice.Fields.processingStatusId.name(), processingStatusId));
            }
        }

        // set the from/thru date filter if they were given
        if (fromInvoiceDate != null) {
            criteria.add(Restrictions.ge(Invoice.Fields.invoiceDate.name(), fromInvoiceDate));
        }
        if (thruInvoiceDate != null) {
            criteria.add(Restrictions.le(Invoice.Fields.invoiceDate.name(), thruInvoiceDate));
        }

        if (fromDueDate != null) {
            criteria.add(Restrictions.ge(Invoice.Fields.dueDate.name(), fromDueDate));
        }
        if (thruDueDate != null) {
            criteria.add(Restrictions.le(Invoice.Fields.dueDate.name(), thruDueDate));
        }

        if (fromPaidDate != null) {
            criteria.add(Restrictions.ge(Invoice.Fields.paidDate.name(), fromPaidDate));
        }
        if (thruPaidDate != null) {
            criteria.add(Restrictions.le(Invoice.Fields.paidDate.name(), thruPaidDate));
        }

        // set the from/thru amount filter if they were given
        if (fromAmount != null) {
            criteria.add(Restrictions.ge(Invoice.Fields.invoiceTotal.name(), fromAmount));
        }
        if (thruAmount != null) {
            criteria.add(Restrictions.le(Invoice.Fields.invoiceTotal.name(), thruAmount));
        }

        if (fromOpenAmount != null) {
            criteria.add(Restrictions.ge(Invoice.Fields.openAmount.name(), fromOpenAmount));
        }
        if (thruOpenAmount != null) {
            criteria.add(Restrictions.le(Invoice.Fields.openAmount.name(), thruOpenAmount));
        }

        // set the other like filters if they were given
        if (UtilValidate.isNotEmpty(referenceNumber)) {
            criteria.add(Restrictions.ilike(Invoice.Fields.referenceNumber.name(), referenceNumber,
                    MatchMode.ANYWHERE));
        }
        if (UtilValidate.isNotEmpty(message)) {
            criteria.add(Restrictions.ilike(Invoice.Fields.invoiceMessage.name(), message, MatchMode.ANYWHERE));
        }
        // order Id search needs a join with OrderItemBilling
        if (UtilValidate.isNotEmpty(orderId)) {
            criteria.createAlias("orderItemBillings", "oib");
            criteria.add(Restrictions.eq("oib." + OrderItemBilling.Fields.orderId.name(), orderId));
        }
        // item description search needs a join with InvoiceItem
        if (UtilValidate.isNotEmpty(itemDescription)) {
            criteria.createAlias("invoiceItems", "ii");
            criteria.add(Restrictions.ilike("ii." + InvoiceItem.Fields.description.name(), itemDescription,
                    MatchMode.ANYWHERE));
        }

        // TODO: accounting tags

        // specify the fields to return
        criteria.setProjection(Projections.projectionList()
                .add(Projections.distinct(Projections.property(Invoice.Fields.invoiceId.name())))
                .add(Projections.property(Invoice.Fields.partyId.name()))
                .add(Projections.property(Invoice.Fields.partyIdFrom.name()))
                .add(Projections.property(Invoice.Fields.statusId.name()))
                .add(Projections.property(Invoice.Fields.processingStatusId.name()))
                .add(Projections.property(Invoice.Fields.invoiceDate.name()))
                .add(Projections.property(Invoice.Fields.dueDate.name()))
                .add(Projections.property(Invoice.Fields.currencyUomId.name()))
                .add(Projections.property(Invoice.Fields.invoiceTotal.name()))
                .add(Projections.property(Invoice.Fields.openAmount.name()))
                .add(Projections.property(Invoice.Fields.referenceNumber.name())));

        // set the order by
        if (orderBy == null) {
            orderBy = Arrays.asList(Invoice.Fields.invoiceDate.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("partyName", "partyId");
        subs.put("partyNameFrom", "partyIdFrom");
        subs.put("invoiceDateString", "invoiceDate");
        subs.put("dueDateString", "dueDate");
        subs.put("statusDescription", "statusId");
        subs.put("processingStatusDescription", "processingStatusId");
        HibernateUtil.setCriteriaOrder(criteria, orderBy, subs);

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

            // convert them into InvoiceViewForListing 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) {
                InvoiceViewForListing r = new InvoiceViewForListing();
                r.initRepository(this);
                int i = 0;
                r.setInvoiceId((String) o[i++]);
                r.setPartyId((String) o[i++]);
                r.setPartyIdFrom((String) o[i++]);
                r.setStatusId((String) o[i++]);
                r.setProcessingStatusId((String) o[i++]);
                r.setInvoiceDate((Timestamp) o[i++]);
                r.setDueDate((Timestamp) o[i++]);
                r.setCurrencyUomId((String) o[i++]);
                r.setInvoiceTotal((BigDecimal) o[i++]);
                r.setOpenAmount((BigDecimal) o[i++]);
                r.setReferenceNumber((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.paxle.data.db.impl.CommandDB.java

License:Open Source License

private List<ICommand> fetchNextCommands(int limit) {
    List<ICommand> result = new ArrayList<ICommand>();

    Session session = null;// www . j  a v a  2  s  .  co  m
    Transaction transaction = null;
    try {
        session = this.sessionFactory.openSession();
        session.setFlushMode(FlushMode.COMMIT);
        session.setCacheMode(CacheMode.IGNORE);
        transaction = session.beginTransaction();

        Query query = session.createQuery("FROM EnqueuedCommand as cmd");
        query.setFetchSize(limit); // this is important for derby because there is no limit support
        query.setMaxResults(limit); // restricting number of returned results
        query.setReadOnly(true); // read-only query
        ScrollableResults sr = query.scroll(ScrollMode.FORWARD_ONLY);

        final Key key = new Key();
        final DynamicBloomFilter bloomFilter = this.bloomFilter;
        final Cache urlExistsCache = this.urlExistsCache;

        // loop through the available commands
        while (sr.next() && result.size() < limit) {
            ICommand cmd = (ICommand) sr.get()[0];

            /* mark command as enqueued */
            session.delete("EnqueuedCommand", cmd);
            session.saveOrUpdate("CrawledCommand", cmd);

            // add command-location into caches
            key.set(cmd.getLocation().toString().getBytes(UTF8), 1.0);
            bloomFilter.add(key);
            Element element = new Element(cmd.getLocation(), null);
            urlExistsCache.put(element);

            result.add(cmd);
        }
        sr.close();

        transaction.commit();
    } catch (Exception e) {
        if (transaction != null && transaction.isActive())
            transaction.rollback();
        this.logger.error("Error while fetching commands", e);
    } finally {
        // closing session
        if (session != null)
            try {
                session.close();
            } catch (Exception e) {
                this.logger.error(
                        String.format("Unexpected '%s' while closing session.", e.getClass().getName()), e);
            }
    }

    return result;
}

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  ww.  j  ava2  s . c  o m
 * <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.xerela.provider.devices.DeviceResolutionElf.java

License:Mozilla Public License

/**
 * Populates a {@link PageData} with the results for the given criteria.
 * @param pageData The page to retrieve.
 * @param criteria The query.//from  w  w  w  . java 2s  .  c  o  m
 * @param sortColumn The sort column or <code>null</code>
 * @param descending <code>true</code> for descending sort, <code>false</code> otherwise.
 * @return The populated page.
 */
public static PageData populatePageData(PageData pageData, Criteria criteria, String sortColumn,
        boolean descending) {
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("populatePageData from criteria: " + criteria.toString()); //$NON-NLS-1$
    }

    criteria.scroll(ScrollMode.SCROLL_INSENSITIVE);

    if (pageData.getOffset() == 0) {
        // Set the total result size into the page data.
        criteria.setProjection(Projections.count(ATTR_DEVICE_ID));
        Object uniqueResult = criteria.uniqueResult();
        if (uniqueResult instanceof Integer) {
            pageData.setTotal((Integer) uniqueResult);
        } else if (uniqueResult instanceof Long) {
            pageData.setTotal(((Long) uniqueResult).intValue());
        } else {
            pageData.setTotal(((BigInteger) uniqueResult).intValue());
        }

        criteria.setProjection(null);
    }

    if (sortColumn != null) {
        if (sortColumn.equals(ATTR_IP_ADDRESS)) {
            criteria.addOrder(descending ? Order.desc(ATTR_IP_HIGH) : Order.asc(ATTR_IP_HIGH))
                    .addOrder(descending ? Order.desc(ATTR_IP_LOW) : Order.asc(ATTR_IP_LOW));
        } else {
            criteria.addOrder((descending ? Order.desc(sortColumn.trim()) : Order.asc(sortColumn.trim())));
        }
    }

    List<ZDeviceLite> list = new ArrayList<ZDeviceLite>();
    ScrollableResults scroll = criteria.scroll();
    while (scroll.next()) {
        Object[] objects = scroll.get();
        list.add((ZDeviceLite) objects[0]);
    }
    scroll.close();

    pageData.setDevices(list.toArray(new ZDeviceLite[0]));

    return pageData;
}

From source file:resource.dao.base.HQLDAO.java

public Object doInHibernate(Session session) throws HibernateException {
    if (logger.isDebugEnabled()) {
        logger.debug("doInHibernate(Session) - start"); //$NON-NLS-1$
    }/*from www  .j  a v a 2  s. c om*/
    Query queryObject = session.createQuery(queryCondition.getQueryString());
    String countHQL = HqlUtils.transferCountHQL(queryCondition.getQueryString());
    if (logger.isInfoEnabled()) {
        logger.info("COUNTHQL = " + countHQL);
    }
    Query queryCount = session.createQuery(countHQL);
    Long totleCount = (Long) queryCount.uniqueResult();

    PageQueryResult queryResult = new PageQueryResult();
    queryResult.setQueryResult(new ArrayList());
    queryResult.setTotalCount(totleCount.intValue());
    if (totleCount > 0) {
        int pageSize = queryCondition.getPageSize();
        int pageIndex = queryCondition.getPageIndex() - 1;
        int startRowNum = pageIndex * pageSize;
        queryObject.setFirstResult(startRowNum);
        queryObject.setMaxResults(pageSize);
        ScrollableResults sr = queryObject.scroll();
        while (sr.next()) {
            queryResult.getQueryResult().add(sr.get());
        }

    }
    if (logger.isDebugEnabled()) {
        logger.debug("doInHibernate(Session) - end"); //$NON-NLS-1$
    }
    return queryResult;
}

From source file:resource.dao.base.HQLDAO.java

public Object doInHibernate(Session session) throws HibernateException {
    if (logger.isDebugEnabled()) {
        logger.debug("doInHibernate(Session) - start"); //$NON-NLS-1$
    }/*from  w w  w. j a  va2s .c o m*/

    Query queryObject = session.createQuery(queryCondition.getQueryString());
    Object[] values = queryCondition.getObjArray();
    Type[] types = queryCondition.getTypeArray();
    if (null != values) {
        for (int i = 0; i < values.length; i++) {
            if (logger.isDebugEnabled()) {
                logger.debug("i=" + i);
                logger.debug("values[i]=" + values[i]);
                logger.debug("types[i]=" + types[i]);
            }
            if (types != null) {
                queryObject.setParameter(i, values[i], types[i]);
            } else {
                queryObject.setParameter(i, values[i]);
            }
        }
    }

    ScrollableResults sr = null;
    try {
        PageQueryResult queryResult = new PageQueryResult();
        queryResult.setQueryResult(new ArrayList());
        queryResult.setTotalCount(0);

        sr = queryObject.scroll();
        if (false == sr.last()) {

            if (logger.isDebugEnabled()) {
                logger.debug("doInHibernate(Session) - end"); //$NON-NLS-1$
            }
            return queryResult;
        }

        int totalCount = sr.getRowNumber();
        queryResult.setTotalCount(totalCount + 1);

        int pageSize = queryCondition.getPageSize();
        int pageIndex = queryCondition.getPageIndex() - 1;

        int startRowNum = pageIndex * pageSize;
        if (false == sr.setRowNumber(startRowNum)) {
            if (logger.isDebugEnabled()) {
                logger.debug("doInHibernate(Session) - end"); //$NON-NLS-1$
            }
            return queryResult;
        }

        List list = queryResult.getQueryResult();
        for (int i = 0; i < pageSize; i++) {
            list.add(sr.get());
            if (false == sr.next()) {
                break;
            }
        }

        if (logger.isDebugEnabled()) {
            logger.debug("doInHibernate(Session) - end"); //$NON-NLS-1$
        }
        return queryResult;
    } finally {
        if (null != sr)
            sr.close();
    }
}