Example usage for org.hibernate ScrollableResults getRowNumber

List of usage examples for org.hibernate ScrollableResults getRowNumber

Introduction

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

Prototype

int getRowNumber();

Source Link

Document

Get the current position in the results.

Usage

From source file:com.lp.server.system.fastlanereader.ZahlungszielHandler.java

License:Open Source License

public QueryResult sort(SortierKriterium[] sortierKriterien, Object selectedId) throws EJBExceptionLP {

    this.getQuery().setSortKrit(sortierKriterien);

    QueryResult result = null;//from w ww  .  j  a v  a 2 s .  c o m
    int rowNumber = 0;

    if (selectedId != null && ((Integer) selectedId).intValue() >= 0) {
        SessionFactory factory = FLRSessionFactory.getFactory();
        Session session = null;

        try {
            session = factory.openSession();
            session = setFilter(session);
            String queryString = getFromClause() + buildWhereClause() + buildOrderByClause();

            Query query = session.createQuery(queryString);
            ScrollableResults scrollableResult = query.scroll();
            if (scrollableResult != null) {
                scrollableResult.beforeFirst();
                while (scrollableResult.next()) {
                    FLRZahlungsziel zahlungsziel = (FLRZahlungsziel) scrollableResult.get(0);
                    Integer id = zahlungsziel.getId();
                    if (selectedId.equals(id)) {
                        rowNumber = scrollableResult.getRowNumber();
                        break;
                    }
                }
            }

        } catch (Exception e) {
            throw new EJBExceptionLP(EJBExceptionLP.FEHLER, e);
        } finally {
            try {
                session.close();
            } catch (HibernateException he) {
                throw new EJBExceptionLP(EJBExceptionLP.FEHLER, he);
            }
        }
    }

    if (rowNumber < 0 || rowNumber >= this.getRowCount()) {
        rowNumber = 0;
    }

    result = this.getPageAt(new Integer(rowNumber));
    result.setIndexOfSelectedRow(rowNumber);

    return result;
}

From source file:com.lynn.dao.BaseDao.java

/**
 * <HQL>//from  w ww  .java  2s .  c  om
 * @param hql HQL?
 * @param countHql ?HQL?
 * @param pageNo 
 * @param pageSize ?
 * @param values ?Object?
 * @return PageResults???????List?
 */
public PageResults<T> findPageByFetchedHql(String hql, String countHql, int pageNo, int pageSize,
        Object... values) {
    PageResults<T> retValue = new PageResults<T>();
    Query query = this.getSession().createQuery(hql);
    if (values != null) {
        for (int i = 0; i < values.length; i++) {
            query.setParameter(i, values[i]);
        }
    }
    int currentPage = pageNo > 1 ? pageNo : 1;
    retValue.setCurrentPage(currentPage);
    retValue.setPageSize(pageSize);
    if (countHql == null) {
        ScrollableResults results = query.scroll();
        results.last();
        retValue.setTotalCount(results.getRowNumber() + 1);// 
    } else {
        Long count = countByHql(countHql, values);
        retValue.setTotalCount(count.intValue());
    }
    retValue.resetPageNo();
    List<T> itemList = query.setFirstResult((currentPage - 1) * pageSize).setMaxResults(pageSize).list();
    if (itemList == null) {
        itemList = new ArrayList<T>();
    }
    retValue.setResults(itemList);

    return retValue;
}

From source file:com.reignite.query.StructuredQuery.java

License:Open Source License

private int runQuery(Criteria criteria, QueryResult result, int maxResults) {
    ScrollableResults scroll = criteria.scroll(ScrollMode.FORWARD_ONLY);
    int count = 0;
    if (scroll.setRowNumber(startIndex)) {
        while (count < maxResults) {
            Object[] row = scroll.get();
            count = fillResult(result, row) ? count += 1 : count;
            if (!scroll.next()) {
                break;
            }//from   w  w w . j  a  va 2s  .c  om
        }
    }
    int totalResultCount = 0;
    if (scroll.last()) {
        totalResultCount = scroll.getRowNumber() + 1;
    }
    result.setTotalResults(totalResultCount);
    scroll.close();
    return count;
}

From source file:de.innovationgate.webgate.api.jdbc.WGSQLResultSet.java

License:Open Source License

private int getNormalQueryResults(String query) {
    ScrollableResults scroll = getQuery().scroll();
    scroll.last();/*  w ww .  ja v  a 2  s.com*/
    return (scroll.getRowNumber() + 1);
}

From source file:it.eng.qbe.statement.hibernate.HQLDataSet.java

License:Mozilla Public License

private int getResultNumberUsingScrollableResults(org.hibernate.Query hibernateQuery, Session session) {
    int resultNumber = 0;
    logger.debug("Scrolling query " + statement.getQueryString() + " ...");
    ScrollableResults scrollableResults = hibernateQuery.scroll();
    scrollableResults.last();//  w w w.  j a  v a2  s .c  o m
    logger.debug("Scrolled query " + statement.getQueryString());
    resultNumber = scrollableResults.getRowNumber() + 1; // Hibernate ScrollableResults row number starts with 0
    logger.debug("Number of fetched records: " + resultNumber + " for query " + statement.getQueryString());
    resultNumber = resultNumber < 0 ? 0 : resultNumber;
    return resultNumber;
}

From source file:net.firejack.platform.core.store.AbstractStore.java

License:Apache License

@Override
@Transactional(readOnly = true)/*from  w  w w.j a va 2  s .  c om*/
public int count(final List<Criterion> criterions, final Map<String, String> aliases,
        final SpecifiedIdsFilter filter) {
    return getHibernateTemplate().execute(new HibernateCallback<Integer>() {
        @Override
        public Integer doInHibernate(Session session) throws HibernateException, SQLException {
            Criteria criteria = createCriteriaForFilter(session, filter);

            if (aliases != null && !aliases.isEmpty()) {
                for (Map.Entry<String, String> alias : aliases.entrySet()) {
                    criteria.createAlias(alias.getKey(), alias.getValue());
                }
            }

            if (criterions != null && !criterions.isEmpty()) {
                for (Criterion restrictions : criterions) {
                    criteria.add(restrictions);
                }
            }

            ScrollableResults scroll = criteria.scroll();
            return scroll.last() ? scroll.getRowNumber() + 1 : 0;
        }
    });
}

From source file:net.firejack.platform.core.store.BaseStore.java

License:Apache License

public Integer findCountWithFilter(final List<Criterion> criterions, final Map<String, String> aliases,
        final SpecifiedIdsFilter filter, final Projection projection) {
    return getHibernateTemplate().execute(new HibernateCallback<Integer>() {
        public Integer doInHibernate(Session session) throws HibernateException, SQLException {
            Criteria criteria = createCriteriaForFilter(session, filter);

            if (aliases != null && !aliases.isEmpty()) {
                for (Map.Entry<String, String> alias : aliases.entrySet()) {
                    criteria.createAlias(alias.getKey(), alias.getValue(), CriteriaSpecification.LEFT_JOIN);
                }//from  w  w w  .j  av a2s . c  om
            }

            if (criterions != null && !criterions.isEmpty()) {
                for (Criterion restrictions : criterions) {
                    criteria.add(restrictions);
                }
            }

            if (projection != null) {
                criteria.setProjection(projection);
            }

            ScrollableResults scroll = criteria.scroll();
            return scroll.last() ? scroll.getRowNumber() + 1 : 0;
        }
    });
}

From source file:net.firejack.platform.core.store.BaseStore.java

License:Apache License

@SuppressWarnings("unchecked")
@Transactional(readOnly = true)//from  w ww  . ja v a  2s  .  c  o m
public int count(final String queryName, final boolean useScroll, final Object... params)
        throws DataAccessException {
    return (Integer) getHibernateTemplate().execute(new HibernateCallback() {
        public Object doInHibernate(Session session) throws HibernateException, SQLException {
            Query query = session.getNamedQuery(queryName);
            setQueryParams(query, params);
            Integer count;
            if (useScroll) {
                ScrollableResults scroll = query.scroll();
                count = scroll.last() ? scroll.getRowNumber() + 1 : 0;
            } else {
                count = ((Number) query.uniqueResult()).intValue();
            }
            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)//from  w  ww. j ava  2  s.  c  o  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:net.mlw.vlh.adapter.hibernate3.HibernateAdapter.java

License:Open Source License

/**
 * @param info/*w w  w .  j a  v a  2 s  .  c  om*/
 * @param results
 * @throws HibernateException
 * @throws NoSuchMethodException
 * @throws InvocationTargetException
 * @throws IllegalAccessException
 */
private void doFocusFor(ValueListInfo info, ScrollableResults results) throws HibernateException {
    info.setFocusStatus(ValueListInfo.FOCUS_NOT_FOUND);

    int currentRow;
    if (isFocusOptimalization()) {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Focusing only property '" + info.getFocusProperty() + "' == '" + info.getFocusValue()
                    + "'.");
        }
        for (currentRow = 0; ((results.next()) && (currentRow < maxRowsForFocus)); currentRow++) {
            String value = results.get(0).toString();
            if (value.equalsIgnoreCase(info.getFocusValue())) {
                if (LOGGER.isInfoEnabled()) {
                    LOGGER.info(
                            "Focus property '" + info.getFocusProperty() + "' in row '" + currentRow + "'.");
                }
                info.setPagingPageFromRowNumber(results.getRowNumber());
                info.setFocusedRowNumberInTable(results.getRowNumber());
                info.setFocusStatus(ValueListInfo.FOCUS_FOUND);
                break;
            }
        }
    } else {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Focusing object with the property '" + info.getFocusProperty() + "' == '"
                    + info.getFocusValue() + "'.");
        }
        for (currentRow = 0; ((results.next()) && (currentRow < maxRowsForFocus)); currentRow++) {

            Object value;
            try {
                value = PropertyUtils.getProperty(results.get(0), info.getFocusProperty());
            } catch (HibernateException e) {
                LOGGER.error("Error getting focus property '" + info.getFocusProperty() + "'", e);
                throw e;
            } catch (Exception e) {
                LOGGER.warn("Ingoring error while getting focus property '" + info.getFocusProperty() + "'", e);
                continue;
            }

            if (value.toString().equalsIgnoreCase(info.getFocusValue())) {
                if (LOGGER.isInfoEnabled()) {
                    LOGGER.info("Focus object's property '" + info.getFocusProperty()
                            + "' was found in the row '" + currentRow + "'.");
                }
                info.setPagingPageFromRowNumber(results.getRowNumber());
                info.setFocusedRowNumberInTable(results.getRowNumber());
                info.setFocusStatus(ValueListInfo.FOCUS_FOUND);
                break;
            }
        }
    }
    if (currentRow == maxRowsForFocus) {
        if (LOGGER.isInfoEnabled()) {
            LOGGER.info("Focus for property '" + info.getFocusProperty() + "' exceded maximum rows for focus '"
                    + maxRowsForFocus + "'.");
        }
        info.setFocusStatus(ValueListInfo.FOCUS_TOO_MANY_ITEMS);
    }
}