Example usage for javax.persistence Query setFirstResult

List of usage examples for javax.persistence Query setFirstResult

Introduction

In this page you can find the example usage for javax.persistence Query setFirstResult.

Prototype

Query setFirstResult(int startPosition);

Source Link

Document

Set the position of the first result to retrieve.

Usage

From source file:br.org.indt.ndg.server.result.ResultHandlerBean.java

@Override
public QueryInputOutputVO getResultListDB(String surveyId, QueryInputOutputVO queryIOVO)
        throws MSMApplicationException, MSMSystemException {
    if (queryIOVO == null) {
        queryIOVO = new QueryInputOutputVO();
    }/*from ww w  .j  a  va2  s .  c om*/

    MSMBusinessDelegate bd = new MSMBusinessDelegate();

    String sqlCommand = "SELECT U FROM Result U WHERE survey.idSurvey = " + surveyId;

    if ((queryIOVO.getFilterText() != null) && (queryIOVO.getFilterFields() != null)) {
        sqlCommand += SqlUtil.getFilterCondition(queryIOVO.getFilterText(), queryIOVO.getFilterFields());
    }

    if ((queryIOVO.getSortField() != null) && (queryIOVO.getIsDescending() != null)) {
        sqlCommand += SqlUtil.getSortCondition(queryIOVO.getSortField(), queryIOVO.getIsDescending());
    }

    Query q = manager.createQuery(sqlCommand);
    queryIOVO.setRecordCount(q.getResultList().size());

    if ((queryIOVO.getPageNumber() != null) && (queryIOVO.getRecordsPerPage() != null)) {
        q.setFirstResult((queryIOVO.getPageNumber() - 1) * queryIOVO.getRecordsPerPage());
        q.setMaxResults(queryIOVO.getRecordsPerPage());
    }

    ArrayList<Object> resultList = new ArrayList<Object>();
    ArrayList<Result> resultsListDB = (ArrayList<Result>) q.getResultList();
    ArrayList<ResultVO> notNullResults = new ArrayList<ResultVO>();

    for (Result result : resultsListDB) {
        Collection<TransactionLogVO> logs = bd.getResultReceived(surveyId, result.getIdResult());
        HashMap<String, TransactionLogVO> map = new HashMap<String, TransactionLogVO>();

        for (TransactionLogVO rlog : logs) {
            map.put(rlog.getResultId(), rlog);
        }

        ResultVO bean = new ResultVO();

        try {
            Result currentResult = manager.find(Result.class, result.getIdResult());

            bean.setIdResult(currentResult.getIdResult());
            bean.setSurveyId(currentResult.getSurvey().getIdSurvey());
            bean.setImei(currentResult.getImei().getImei());

            if ((currentResult.getTitle() == null) || (currentResult.getLatitude() == null)
                    || (currentResult.getLongitude() == null)) {
                ResultParser parser = new ResultParser();
                ResultXml resultXML = parser.parseResult(new StringBuffer(result.getResultXml()), "UTF-8");

                bean.setTitle(resultXML.getTitle());
                bean.setLat(resultXML.getLatitude());
                bean.setLon(resultXML.getLongitude());

                currentResult.setTitle(resultXML.getTitle());
                currentResult.setLatitude(resultXML.getLatitude());
                currentResult.setLongitude(resultXML.getLongitude());

                manager.merge(currentResult);
            } else {
                bean.setTitle(currentResult.getTitle());
                bean.setLat(currentResult.getLatitude());
                bean.setLon(currentResult.getLongitude());
            }

            if (!logs.isEmpty()) {
                TransactionLogVO t = map.get(result.getIdResult());

                if (t != null) {
                    bean.setDate(SystemUtils.toDate(t.getDtLog()));
                    bean.setUser(t.getUser());
                }
            }

            // order results by title - ascending
            if (bean.getTitle() == null) {
                resultList.add(bean);
            } else {
                if (notNullResults.size() == 0) {
                    notNullResults.add(bean);
                } else {
                    if (bean.getTitle().compareToIgnoreCase(
                            notNullResults.get(notNullResults.size() - 1).getTitle()) > 0) {
                        notNullResults.add(bean);
                    } else {
                        notNullResults.add(notNullResults.size() - 1, bean);
                    }
                }
            }
        } catch (Exception e) {
            throw new ResultNotParsedException();
        }
    }

    // results without title come first
    resultList.addAll(notNullResults);

    queryIOVO.setQueryResult(resultList);

    return queryIOVO;
}

From source file:com.sun.socialsite.business.impl.JPAAppManagerImpl.java

/**
 * Note: using SuppressWarnings annotation because the JPA API is not genericized.
 *//*from  w  ww . ja va  2  s. c  o m*/
@SuppressWarnings(value = "unchecked")
public List<App> getApps(int offset, int length) throws SocialSiteException {
    Query query = strategy.getNamedQuery("App.getAll");
    if (offset != 0) {
        query.setFirstResult(offset);
    }
    if (length != -1) {
        query.setMaxResults(length);
    }
    return (List<App>) query.getResultList();
}

From source file:com.sun.socialsite.business.impl.JPAAppManagerImpl.java

/**
 * Note: using SuppressWarnings annotation because the JPA API is not genericized.
 *///w w w  .j  a  v a 2  s.  co  m
@SuppressWarnings(value = "unchecked")
public List<App> getOldestApps(int offset, int length) throws SocialSiteException {
    Query query = strategy.getNamedQuery("App.getOldest");
    if (offset != 0) {
        query.setFirstResult(offset);
    }
    if (length != -1) {
        query.setMaxResults(length);
    }
    return (List<App>) query.getResultList();
}

From source file:com.sun.socialsite.business.impl.JPAAppManagerImpl.java

/**
 * Note: using SuppressWarnings annotation because the JPA API is not genericized.
 *///from  w w w .  j  a v a  2 s.  c  om
@SuppressWarnings(value = "unchecked")
public List<App> getAppsInDirectory(int offset, int length) throws SocialSiteException {
    Query query = strategy.getNamedQuery("App.getAllInDirectory");
    if (offset != 0) {
        query.setFirstResult(offset);
    }
    if (length != -1) {
        query.setMaxResults(length);
    }
    return (List<App>) query.getResultList();
}

From source file:org.sofun.core.member.MemberServiceImpl.java

@SuppressWarnings("unchecked")
@Override//  w  ww.ja va 2 s . c om
public List<MemberTransaction> getUnAckWinningsTransactionsFor(Member member) {

    String queryStr = "from " + MemberTransactionImpl.class.getSimpleName()
            + " t where t.member.id=:member_id AND t.credit=:credit AND t.type=:type AND t.ack=:ack ORDER BY txn_date DESC";
    Query query = createQuery(queryStr);
    query.setParameter("member_id", member.getId());
    query.setParameter("type", MemberTransactionType.BET_CREDIT);
    query.setParameter("credit", true);
    query.setParameter("ack", false);

    // TMP
    query.setFirstResult(0);
    query.setMaxResults(1);

    try {
        return query.getResultList();
    } catch (NoResultException nre) {
        return new ArrayList<MemberTransaction>();
    }

}

From source file:de.micromata.genome.db.jpa.logging.BaseJpaLoggingImpl.java

/**
 * {@inheritDoc}/* w ww  .  java 2  s  .  c om*/
 *
 */

@Override
protected void selectLogsImpl(Timestamp start, Timestamp end, Integer loglevel, String category, String msg,
        List<Pair<String, String>> logAttributes, final int startRow, final int maxRow, List<OrderBy> orderBy,
        final boolean masterOnly, final LogEntryCallback callback) throws EndOfSearch {

    final StopWatch sw = new StopWatch();
    sw.start();

    final StringBuilder queryStringBuilder = new StringBuilder(
            "select lm from " + getMasterClass().getName() + "  as lm");
    if (masterOnly == false) {
        queryStringBuilder.append(" left outer join fetch lm.attributes");
    }

    boolean firstWhere = true;
    // final List<Object> args = new ArrayList<Object>();
    Map<String, Object> argmap = new HashMap<>();
    if (start != null) {
        firstWhere = addWhere(queryStringBuilder, firstWhere, "lm.createdAt >= :createdAtMin");
        argmap.put("createdAtMin", start);
    }
    if (end != null) {
        firstWhere = addWhere(queryStringBuilder, firstWhere, "lm.createdAt <= :createdAtMax");
        argmap.put("createdAtMax", end);
    }
    if (loglevel != null) {
        firstWhere = addWhere(queryStringBuilder, firstWhere, "lm.loglevel >= :logLevelMin");
        argmap.put("logLevelMin", new Short(loglevel.shortValue()));
    }
    if (StringUtils.isNotBlank(category) == true) {
        firstWhere = addWhere(queryStringBuilder, firstWhere, "lm.category = :category");
        argmap.put("category", category);
    }
    if (StringUtils.isNotBlank(msg) == true) {
        firstWhere = addWhere(queryStringBuilder, firstWhere, "lm.shortmessage like :message");
        argmap.put("message", msg + "%");
    }
    if (logAttributes != null) {
        int attrNum = 0;
        for (Pair<String, String> pat : logAttributes) {
            ++attrNum;
            LogAttributeType at = getAttributeTypeByString(pat.getFirst());
            if (at == null) {
                GLog.warn(GenomeLogCategory.Configuration,
                        "SelLogs; Cannot find LogAttribute: " + pat.getFirst());
                continue;
            }
            if (at.isSearchKey() == false) {
                GLog.warn(GenomeLogCategory.Configuration,
                        "SelLogs; LogAttribute not searchable: " + pat.getFirst());
                continue;
            }
            if (StringUtils.contains(pat.getSecond(), "%") == false) {
                firstWhere = addWhere(queryStringBuilder, firstWhere, at.columnName(), " = :attr" + attrNum);
            } else {
                firstWhere = addWhere(queryStringBuilder, firstWhere, at.columnName(), " like :attr" + attrNum);
            }

            argmap.put("attr" + attrNum, pat.getSecond());
        }
    }

    if (CollectionUtils.isEmpty(orderBy) == false) {
        queryStringBuilder.append(" order by ");
        boolean first = true;
        for (OrderBy order : orderBy) {
            if (first == true) {
                first = false;
            } else {
                queryStringBuilder.append(", ");
            }
            String propertyName = convertColumnNameToPropertyName(order.getColumn());
            queryStringBuilder.append("lm.").append((propertyName != null) ? propertyName : order.getColumn()); // eventually
            // requires
            // translation
            // to
            // propertynames
            queryStringBuilder.append(order.isDescending() ? " desc" : " asc");
        }
    }

    EmgrFactory<DefaultEmgr> mgrfac = getEmgrFactory();
    mgrfac.runInTrans(new EmgrCallable<Void, DefaultEmgr>() {
        @Override
        public Void call(DefaultEmgr mgr) {

            Query query = mgr.createQuery(queryStringBuilder.toString());
            for (Map.Entry<String, Object> arg : argmap.entrySet()) {
                query.setParameter(arg.getKey(), arg.getValue());
            }
            query.setFirstResult(startRow);
            if (masterOnly == true) {
                query.setMaxResults(maxRow);
            } else {
                query.setMaxResults(maxRow * 10); // pessimistic assumption:
                // 10 attributes per
                // master entry
            }

            List<M> res = query.getResultList();

            for (M lmDo : res) {
                LogEntry le = new LogEntry();
                copyMasterFields(le, lmDo, masterOnly);
                try {
                    callback.onRow(le);
                } catch (EndOfSearch eos) {
                    break;
                }
            }
            return null;
        }
    });
}

From source file:uk.ac.edukapp.service.WidgetProfileService.java

@SuppressWarnings("unchecked")
public SearchResults returnWidgetProfilesOrderedByDate(int rows, int offset) {
    List<Widgetprofile> widgetprofiles;
    EntityManager entityManager = getEntityManagerFactory().createEntityManager();
    Query wpQuery = entityManager.createNamedQuery("Widgetprofile.created");
    wpQuery.setFirstResult(offset);
    wpQuery.setMaxResults(rows);/*  w  w  w.j a va  2s  .  c  om*/
    widgetprofiles = (List<Widgetprofile>) wpQuery.getResultList();
    entityManager.close();
    SearchResults sr = new SearchResults();
    sr.setWidgets(widgetprofiles);
    return sr;
}

From source file:edu.kit.dama.mdm.core.jpa.MetaDataManagerJpa.java

@Override
public final List findResultList(String queryString, Object[] pParameters, int pFirstIdx, int pMaxResults)
        throws UnauthorizedAccessAttemptException {
    List result = new ArrayList();
    try {//  w w w .  j a  va 2 s . c o m
        Query q = entityManager.createQuery(queryString);
        applyProperties(q);
        if (pParameters != null && pParameters.length != 0) {
            for (int i = 0; i < pParameters.length; i++) {
                q.setParameter(i + 1, pParameters[i]);
            }
        }
        q.setFirstResult((pFirstIdx >= 0) ? pFirstIdx : 0);
        if (pMaxResults > 0) {
            q.setMaxResults(pMaxResults);
        }
        result = q.getResultList();
    } catch (RuntimeException re) {
        LOGGER.warn("Failed to obtain generic query result list", re);
    } finally {
        finalizeEntityManagerAccess("find result list with plain SQL '" + queryString + "'", null, List.class);
    }
    return result;
}

From source file:org.esbtools.message.admin.common.EsbMessageAdminServiceImpl.java

/**
 * Returns error message of the given queue
 * @param criteria/*from ww  w.  j  a v  a 2  s  .  c  o  m*/
 * @param fromDate
 * @param toDate
 * @param sortField
 * @param sortAsc
 * @param start
 * @param maxResults
 * @return SearchResult
 */
public SearchResult findMessagesBySearchCriteria(SearchCriteria criteria, Date fromDate, Date toDate,
        String sortField, Boolean sortAsc, Integer start, Integer maxResults) {

    SearchResult result = new SearchResult();
    long startTime = System.currentTimeMillis();

    // allow sorting only by display fields, choose time stamp if proper field is not set.
    String sortBy = (sortField == null || !getSortingFields().contains(sortField)) ? "timestamp" : sortField;

    if (maxResults > 0) {
        Query countQuery = getQueryFromCriteria(criteria, sortBy, sortAsc, fromDate, toDate, true);
        try {
            result.setTotalResults((Long) countQuery.getSingleResult());
        } catch (NoResultException e) {
            LOG.warn("No result when trying to do count of searchResults", e);
            return SearchResult.empty();
        }

        Query resultQuery = getQueryFromCriteria(criteria, sortBy, sortAsc, fromDate, toDate, false);

        resultQuery.setFirstResult(start);
        resultQuery.setMaxResults(maxResults);
        @SuppressWarnings("rawtypes")
        List searchResult = resultQuery.getResultList();

        EsbMessage[] resultMessages = new EsbMessage[searchResult.size()];
        for (int i = 0; i < resultMessages.length; i++) {
            Object[] cols = (Object[]) searchResult.get(i);
            EsbMessage msg = new EsbMessage();
            msg.setId((Long) cols[0]);
            msg.setTimestamp((Date) cols[1]);
            msg.setMessageType((String) cols[2]);
            msg.setSourceSystem((String) cols[3]);
            msg.setErrorSystem((String) cols[4]);
            msg.setOccurrenceCount((Integer) cols[5]);
            msg.setResubmittedOn((Date) cols[6]);
            msg.setAllowsResubmit(allowsResubmit(msg));
            msg.setEditableMessage(isEditableMessage(msg));
            resultMessages[i] = msg;
        }
        result.setMessages(resultMessages);
        result.setItemsPerPage(maxResults);
        result.setPage((start / maxResults) + 1);
    } else {
        result.setItemsPerPage(0);
        result.setPage(0);
    }
    long endTime = System.currentTimeMillis();
    saveAuditEvent(new AuditEvent(DEFAULT_USER, "SEARCH", ERROR_KEY_TYPE, "", "",
            criteria.toString() + ", From:" + fromDate + ", To:" + toDate + ", Sort:" + sortField + ", Asc:"
                    + sortAsc + ", start:" + start + ", maxResults:" + maxResults + " time:"
                    + (endTime - startTime)));

    return result;
}

From source file:org.cesecore.audit.impl.integrityprotected.IntegrityProtectedAuditorSessionBean.java

/**
 * Build a JPA Query from the supplied queryStr and criteria.
 * Optionally using startIndex and resultLimit (used if >0).
 *//*from w  w w  .j  a  va  2s.  c o  m*/
private Query buildConditionalQuery(final EntityManager entityManager, final String queryStr,
        final QueryCriteria criteria, final int startIndex, final int resultLimit) {
    Query query = null;
    if (criteria == null) {
        query = entityManager.createQuery(queryStr);
    } else {
        QueryGenerator generator = QueryGenerator.generator(AuditRecordData.class, criteria, "a");
        final String conditions = generator.generate();
        query = entityManager.createQuery(queryStr + conditions);
        for (final String key : generator.getParameterKeys()) {
            final Object param = generator.getParameterValue(key);
            query.setParameter(key, param);
        }
    }
    if (resultLimit > 0) {
        query.setMaxResults(resultLimit);
    }
    if (startIndex > 0) {
        query.setFirstResult(startIndex - 1);
    }
    return query;
}