Example usage for org.hibernate ScrollableResults beforeFirst

List of usage examples for org.hibernate ScrollableResults beforeFirst

Introduction

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

Prototype

void beforeFirst();

Source Link

Document

Go to a location just before first result, This is the location of the cursor on a newly returned scrollable result.

Usage

From source file:gov.nih.nci.caarray.plugins.nimblegen.NdfHandler.java

License:BSD License

private int loadProbes(ArrayDesignDetails details, Map<String, LogicalProbe> logicalProbes,
        ScrollableResults results) throws IOException {
    int count = 0;
    results.beforeFirst();
    String lastSeqId = null;//from  w w  w. j ava2  s. c  om
    while (results.next()) {
        final Object[] values = results.get();
        final Map<String, Object> vals = new HashMap<String, Object>();
        vals.put(PROBE_ID, values[0]);
        vals.put(SEQ_ID, values[1]);
        vals.put(CONTAINER2, values[2]);
        vals.put(X, values[3]);
        vals.put(Y, values[4]);

        if (lastSeqId != null && !vals.get(SEQ_ID).equals(lastSeqId)) {
            logicalProbes.clear();
            flushAndClearSession();
        }
        lastSeqId = (String) vals.get(SEQ_ID);

        final PhysicalProbe p = createPhysicalProbe(details, vals, logicalProbes);
        getArrayDao().save(p);
        ++count;
    }
    return count;
}

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)// ww  w . j  av a 2 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.glite.security.voms.admin.persistence.tools.DeleteRecordsCommand.java

License:Apache License

@Override
public void execute(CommandLine line) {

    AuditSearchDAO dao = DAOFactory.instance().getAuditSearchDAO();
    AuditLogSearchParams params = addConstraintsFromCommandLine(line);

    ScrollableAuditLogSearchResults results = dao.scrollEventsMatchingParams(params,
            ScrollMode.SCROLL_INSENSITIVE);

    int count = 0;
    ScrollableResults scroll = results.getResults();

    scroll.last();//from w ww  .j ava 2s .  co  m
    count = scroll.getRowNumber();

    if (count + 1 == 0) {
        System.out.println("No events found");
        return;
    }

    System.out.format("%d records will be deleted. Type 'yes' if you want to continue\n", count + 1);

    try {
        if (!getConfirmationFromUser()) {
            System.out.println("Aborting on user's request.");
            return;
        }
    } catch (IOException e) {
        throw new AuditLogCommandError(e);
    }

    scroll.beforeFirst();
    System.out.println("Deleting events:");

    count = 0;

    while (scroll.next()) {
        count++;
        AuditEvent event = (AuditEvent) scroll.get()[0];

        printAuditLogEvent(event);
        dao.makeTransient(event);
        dao.flush();
        HibernateFactory.getSession().evict(event);
    }

    System.out.format("%d events deleted.\n", count);

}

From source file:org.openbravo.advpaymentmngt.utility.FIN_BankStatementImport.java

License:Open Source License

private String closest(ScrollableResults businessPartners, String partnername) {
    String targetBusinessPartnerId = "";
    try {/*w w  w  . j  a va  2 s  . c  o m*/
        businessPartners.beforeFirst();
        businessPartners.next();
        Object[] resultObject = (Object[]) businessPartners.get(0);

        String targetBusinessPartnerName = "";
        if (resultObject.getClass().isArray()) {
            final Object[] values = resultObject;
            targetBusinessPartnerId = (String) values[0];
            targetBusinessPartnerName = (String) values[1];
        }

        int distance = StringUtils.getLevenshteinDistance(partnername, targetBusinessPartnerName);
        String parsedPartnername = partnername.toLowerCase();
        // Remove exceptions
        for (String eliminate : stringExceptions) {
            parsedPartnername = parsedPartnername.replaceAll(eliminate.toLowerCase(), "");
        }

        // Remove Numeric characters
        char[] digits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
        for (char character : digits) {
            parsedPartnername = parsedPartnername.replace(character, ' ');
            parsedPartnername = parsedPartnername.trim();
        }

        businessPartners.beforeFirst();
        int i = 0;
        while (businessPartners.next()) {
            i++;
            String bpId = "";
            String bpName = "";
            resultObject = (Object[]) businessPartners.get(0);
            if (resultObject.getClass().isArray()) {
                final Object[] values = resultObject;
                bpId = (String) values[0];
                bpName = (String) values[1];
            }
            // Calculates distance between two strings meaning number of changes required for a string
            // to
            // convert in another string
            int bpDistance = StringUtils.getLevenshteinDistance(parsedPartnername, bpName.toLowerCase());
            if (bpDistance < distance) {
                distance = bpDistance;
                targetBusinessPartnerId = bpId;
            }
            if (i % 100 == 0) {
                OBDal.getInstance().flush();
                OBDal.getInstance().getSession().clear();
            }
        }
        return targetBusinessPartnerId;
    } catch (Exception e) {
        log4j.error(e.getStackTrace());
    } finally {
        return targetBusinessPartnerId;
    }

}

From source file:org.openbravo.common.actionhandler.SetNewBPCurrency.java

License:Open Source License

@Override
protected JSONObject doExecute(Map<String, Object> parameters, String content) {

    JSONObject jsonRequest = null;//from  ww w  .j  a  v a2  s.c  o m
    OBContext.setAdminMode(true);
    try {
        jsonRequest = new JSONObject(content);
        JSONObject params = jsonRequest.getJSONObject("_params");
        final String strOrgId = jsonRequest.getString("inpadOrgId");
        final String strFromCurrencyId = jsonRequest.getString("inpbpCurrencyId");
        final String strToCurrencyId = params.getString("C_Currency_ID");
        final String strRate = params.getString("Rate");
        final String strAmount = params.getString("Foreign_Amount");
        final boolean strSetAmount = params.getBoolean("Amount");
        final boolean strUseDefaultConversion = params.getBoolean("Default_Conversion_Rate");
        final String strBpartnerId = jsonRequest.getString("C_BPartner_ID");
        final String glItemId = params.getString("c_glitem_id");
        BigDecimal creditUsed = BigDecimal.ZERO;
        BigDecimal rate = BigDecimal.ZERO;
        Double amount = new Double(0);
        if (strSetAmount && !"null".equals(strAmount)) {
            amount = Double.parseDouble(strAmount);
        }

        if (strUseDefaultConversion && !strSetAmount) {
            rate = getConversionRate(strOrgId, strFromCurrencyId, strToCurrencyId);
            if (rate == BigDecimal.ZERO && !strFromCurrencyId.equals(strToCurrencyId)) {
                try {
                    jsonRequest = new JSONObject();
                    String message = OBMessageUtils.messageBD("NoCurrencyConversion");
                    JSONObject errorMessage = new JSONObject();
                    errorMessage.put("severity", "error");
                    errorMessage.put("text", message);
                    jsonRequest.put("message", errorMessage);
                } catch (Exception e) {
                    OBDal.getInstance().rollbackAndClose();
                    log.error(e.getMessage(), e);
                }
                return jsonRequest;
            }
        } else {
            rate = "null".equals(strRate) ? BigDecimal.ZERO : BigDecimal.valueOf(Double.parseDouble(strRate));
        }
        BusinessPartner businessPartner = OBDal.getInstance().get(BusinessPartner.class, strBpartnerId);
        creditUsed = businessPartner.getCreditUsed();

        ScrollableResults scroll = null;
        GLItem glItem = OBDal.getInstance().get(GLItem.class, glItemId);
        Currency currency = OBDal.getInstance().get(Currency.class, strToCurrencyId);
        BigDecimal creditAmount = BigDecimal.ZERO;
        BigDecimal creditRate = BigDecimal.ONE;

        // Convert available credit automatically
        if (!StringUtils.equals(strFromCurrencyId, strToCurrencyId) && !StringUtils.isEmpty(glItemId)
                && !StringUtils.equals(glItemId, "null")) {

            // Get the rate
            if (!strSetAmount) {
                creditRate = rate;
            } else if (creditUsed.compareTo(BigDecimal.ZERO) != 0) {
                creditRate = BigDecimal.valueOf(amount).divide(creditUsed,
                        FIN_Utility.getConversionRatePrecision(RequestContext.get().getVariablesSecureApp()),
                        RoundingMode.HALF_UP);
            }

            // Loop through all payment documents which generate credit
            scroll = FinancialUtils.getPaymentsWithCredit(businessPartner.getId(), strFromCurrencyId);
            int i = 0;
            try {
                while (scroll.next()) {
                    final String paymentCreditId = (String) scroll.get()[0];
                    final FIN_Payment paymentCredit = OBDal.getInstance().get(FIN_Payment.class,
                            paymentCreditId);
                    creditAmount = paymentCredit.getGeneratedCredit().subtract(paymentCredit.getUsedCredit());

                    // Create a payment to consume the credit with a glitem
                    FIN_Payment payment1 = (FIN_Payment) DalUtil.copy(paymentCredit, false);
                    payment1.setPaymentDate(new Date());
                    payment1.setAmount(creditAmount);
                    payment1.setDocumentNo(FIN_Utility.getDocumentNo(payment1.getOrganization(),
                            payment1.getDocumentType().getDocumentCategory(), "DocumentNo_FIN_Payment"));
                    payment1.setProcessed(false);
                    payment1.setPosted("N");
                    payment1.setDescription(null);
                    payment1.setGeneratedCredit(BigDecimal.ZERO);
                    payment1.setUsedCredit(BigDecimal.ZERO);

                    // Create a payment detail to consume the credit with a glitem
                    FIN_PaymentDetail paymentDetail1 = OBProvider.getInstance().get(FIN_PaymentDetail.class);
                    paymentDetail1.setClient(paymentCredit.getClient());
                    paymentDetail1.setOrganization(paymentCredit.getOrganization());
                    paymentDetail1.setFinPayment(payment1);
                    paymentDetail1.setAmount(creditAmount);
                    paymentDetail1.setRefund(false);
                    paymentDetail1.setGLItem(glItem);
                    paymentDetail1.setPrepayment(false);

                    // Create a payment schedule detail to consume the credit with a glitem
                    FIN_PaymentScheduleDetail paymentScheduleDetail1 = OBProvider.getInstance()
                            .get(FIN_PaymentScheduleDetail.class);
                    paymentScheduleDetail1.setClient(paymentCredit.getClient());
                    paymentScheduleDetail1.setOrganization(paymentCredit.getOrganization());
                    paymentScheduleDetail1.setPaymentDetails(paymentDetail1);
                    paymentScheduleDetail1.setAmount(creditAmount);

                    // Process the payment
                    paymentDetail1.getFINPaymentScheduleDetailList().add(paymentScheduleDetail1);
                    payment1.getFINPaymentDetailList().add(paymentDetail1);
                    OBDal.getInstance().save(payment1);
                    OBDal.getInstance().save(paymentDetail1);
                    OBDal.getInstance().save(paymentScheduleDetail1);
                    FIN_PaymentProcess.doProcessPayment(payment1, "D", false, null, null);

                    // Modify description of original credit payment
                    String paymentCreditDesc = paymentCredit.getDescription() + "\n" + String.format(
                            OBMessageUtils.messageBD("APRM_CreditUsedPayment"), payment1.getDocumentNo());
                    paymentCredit.setDescription((paymentCreditDesc.length() > 255)
                            ? paymentCreditDesc.substring(0, 251).concat("...").toString()
                            : paymentCreditDesc.toString());

                    // Create a payment to refund the credit
                    FIN_Payment payment2 = (FIN_Payment) DalUtil.copy(paymentCredit, false);
                    payment2.setPaymentDate(new Date());
                    payment2.setAmount(creditAmount.negate());
                    payment2.setDocumentNo(FIN_Utility.getDocumentNo(payment2.getOrganization(),
                            payment2.getDocumentType().getDocumentCategory(), "DocumentNo_FIN_Payment"));
                    payment2.setProcessed(false);
                    payment2.setPosted("N");
                    payment2.setDescription(
                            OBMessageUtils.messageBD("APRM_RefundPayment") + ": " + payment1.getDocumentNo());
                    payment2.setGeneratedCredit(BigDecimal.ZERO);
                    payment2.setUsedCredit(creditAmount);

                    // Create a payment credit to refund the credit
                    FIN_Payment_Credit paymentCredit2 = OBProvider.getInstance().get(FIN_Payment_Credit.class);
                    paymentCredit2.setClient(paymentCredit.getClient());
                    paymentCredit2.setOrganization(paymentCredit.getOrganization());
                    paymentCredit2.setPayment(payment2);
                    paymentCredit2.setCreditPaymentUsed(paymentCredit);
                    paymentCredit2.setAmount(creditAmount);
                    paymentCredit2.setCurrency(paymentCredit.getCurrency());

                    // Create a payment detail to refund the credit
                    FIN_PaymentDetail paymentDetail2 = OBProvider.getInstance().get(FIN_PaymentDetail.class);
                    paymentDetail2.setClient(paymentCredit.getClient());
                    paymentDetail2.setOrganization(paymentCredit.getOrganization());
                    paymentDetail2.setFinPayment(payment2);
                    paymentDetail2.setAmount(creditAmount.negate());
                    paymentDetail2.setRefund(true);
                    paymentDetail2.setPrepayment(true);

                    // Create a payment schedule detail to refund the credit
                    FIN_PaymentScheduleDetail paymentScheduleDetail2 = OBProvider.getInstance()
                            .get(FIN_PaymentScheduleDetail.class);
                    paymentScheduleDetail2.setClient(paymentCredit.getClient());
                    paymentScheduleDetail2.setOrganization(paymentCredit.getOrganization());
                    paymentScheduleDetail2.setPaymentDetails(paymentDetail2);
                    paymentScheduleDetail2.setAmount(creditAmount.negate());

                    // Process the payment
                    paymentDetail2.getFINPaymentScheduleDetailList().add(paymentScheduleDetail2);
                    payment2.getFINPaymentDetailList().add(paymentDetail2);
                    payment2.getFINPaymentCreditList().add(paymentCredit2);
                    paymentCredit.setUsedCredit(creditAmount);
                    OBDal.getInstance().save(paymentCredit);
                    OBDal.getInstance().save(payment2);
                    OBDal.getInstance().save(paymentCredit2);
                    OBDal.getInstance().save(paymentDetail2);
                    OBDal.getInstance().save(paymentScheduleDetail2);
                    FIN_PaymentProcess.doProcessPayment(payment2, "D", false, null, null);

                    i++;
                    if (i % 100 == 0) {
                        OBDal.getInstance().flush();
                        OBDal.getInstance().getSession().clear();
                    }
                }

                // Set the new currency
                businessPartner.setCurrency(currency);

                // Loop through all payment documents which generate credit
                scroll.beforeFirst();
                i = 0;
                while (scroll.next()) {
                    final String paymentCreditId = (String) scroll.get()[0];
                    final FIN_Payment paymentCredit = OBDal.getInstance().get(FIN_Payment.class,
                            paymentCreditId);

                    // Create a payment to create the credit with a glitem
                    FIN_Payment payment3 = (FIN_Payment) DalUtil.copy(paymentCredit, false);
                    payment3.setPaymentDate(new Date());
                    payment3.setCurrency(currency);
                    payment3.setAmount(BigDecimal.ZERO);
                    payment3.setDocumentNo(FIN_Utility.getDocumentNo(payment3.getOrganization(),
                            payment3.getDocumentType().getDocumentCategory(), "DocumentNo_FIN_Payment"));
                    payment3.setProcessed(false);
                    payment3.setPosted("N");
                    payment3.setDescription(null);
                    final BigDecimal generatedCredit = creditAmount.multiply(creditRate)
                            .setScale(currency.getStandardPrecision().intValue(), RoundingMode.HALF_UP);
                    payment3.setGeneratedCredit(generatedCredit);
                    payment3.setUsedCredit(BigDecimal.ZERO);

                    // Create a payment detail to create the credit with a glitem
                    FIN_PaymentDetail paymentDetail3 = OBProvider.getInstance().get(FIN_PaymentDetail.class);
                    paymentDetail3.setClient(paymentCredit.getClient());
                    paymentDetail3.setOrganization(paymentCredit.getOrganization());
                    paymentDetail3.setFinPayment(payment3);
                    paymentDetail3.setAmount(generatedCredit);
                    paymentDetail3.setRefund(false);
                    paymentDetail3.setPrepayment(true);

                    // Create a payment detail to create the credit with a glitem
                    FIN_PaymentDetail paymentDetail4 = OBProvider.getInstance().get(FIN_PaymentDetail.class);
                    paymentDetail4.setClient(paymentCredit.getClient());
                    paymentDetail4.setOrganization(paymentCredit.getOrganization());
                    paymentDetail4.setFinPayment(payment3);
                    paymentDetail4.setAmount(generatedCredit.negate());
                    paymentDetail4.setGLItem(glItem);
                    paymentDetail4.setRefund(false);
                    paymentDetail4.setPrepayment(false);

                    // Create a payment schedule detail to create the credit with a glitem
                    FIN_PaymentScheduleDetail paymentScheduleDetail3 = OBProvider.getInstance()
                            .get(FIN_PaymentScheduleDetail.class);
                    paymentScheduleDetail3.setClient(paymentCredit.getClient());
                    paymentScheduleDetail3.setOrganization(paymentCredit.getOrganization());
                    paymentScheduleDetail3.setPaymentDetails(paymentDetail3);
                    paymentScheduleDetail3.setAmount(generatedCredit);

                    // Create a payment schedule detail to create the credit with a glitem
                    FIN_PaymentScheduleDetail paymentScheduleDetail4 = OBProvider.getInstance()
                            .get(FIN_PaymentScheduleDetail.class);
                    paymentScheduleDetail4.setClient(paymentCredit.getClient());
                    paymentScheduleDetail4.setOrganization(paymentCredit.getOrganization());
                    paymentScheduleDetail4.setPaymentDetails(paymentDetail4);
                    paymentScheduleDetail4.setAmount(generatedCredit.negate());

                    // Process the payment
                    paymentDetail3.getFINPaymentScheduleDetailList().add(paymentScheduleDetail3);
                    paymentDetail4.getFINPaymentScheduleDetailList().add(paymentScheduleDetail4);
                    payment3.getFINPaymentDetailList().add(paymentDetail3);
                    payment3.getFINPaymentDetailList().add(paymentDetail4);
                    OBDal.getInstance().save(payment3);
                    OBDal.getInstance().save(paymentDetail3);
                    OBDal.getInstance().save(paymentDetail4);
                    OBDal.getInstance().save(paymentScheduleDetail3);
                    OBDal.getInstance().save(paymentScheduleDetail4);
                    OBDal.getInstance().save(paymentCredit);
                    FIN_PaymentProcess.doProcessPayment(payment3, "D", false, null, null);

                    i++;
                    if (i % 100 == 0) {
                        OBDal.getInstance().flush();
                        OBDal.getInstance().getSession().clear();
                    }
                }
            } finally {
                scroll.close();
            }
        }

        if (strSetAmount && creditUsed.compareTo(BigDecimal.valueOf(amount)) != 0) {
            businessPartner.setCreditUsed(BigDecimal.valueOf(amount));
        }
        if (!strToCurrencyId.equals(strFromCurrencyId) && strToCurrencyId != null
                && !"null".equals(strToCurrencyId)) {
            businessPartner.setCurrency(OBDal.getInstance().get(Currency.class, strToCurrencyId));
            if (rate.compareTo(BigDecimal.ZERO) != 0 && creditUsed.compareTo(BigDecimal.ZERO) != 0
                    && !strSetAmount) {
                businessPartner.setCreditUsed(creditUsed.multiply(rate));
            }
        }

        String messageText = OBMessageUtils.messageBD("CurrencyUpdated");
        JSONObject msg = new JSONObject();
        msg.put("severity", "success");
        msg.put("text", OBMessageUtils.parseTranslation(messageText));
        jsonRequest.put("message", msg);

    } catch (Exception e) {
        OBDal.getInstance().rollbackAndClose();
        log.error("Error in set new currency Action Handler", e);

        try {
            jsonRequest = new JSONObject();
            Throwable ex = DbUtility.getUnderlyingSQLException(e);
            String message = OBMessageUtils.translateError(ex.getMessage()).getMessage();
            JSONObject errorMessage = new JSONObject();
            errorMessage.put("severity", "error");
            errorMessage.put("text", message);
            jsonRequest.put("message", errorMessage);
        } catch (Exception e2) {
            log.error(e.getMessage(), e2);
            // do nothing, give up
        }
    } finally {
        OBContext.restorePreviousMode();
    }
    return jsonRequest;
}

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());
            }/*www. j  ava 2 s.c  o m*/
            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;
}