Example usage for javax.persistence Query setMaxResults

List of usage examples for javax.persistence Query setMaxResults

Introduction

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

Prototype

Query setMaxResults(int maxResult);

Source Link

Document

Set the maximum number of results to retrieve.

Usage

From source file:org.opentides.persistence.impl.AuditLogDAOImpl.java

@SuppressWarnings("unchecked")
public final List<AuditLog> findByNamedQuery(final String name, final Map<String, Object> params, int start,
        int total) {
    String queryString = getJpqlQuery(name);
    Query queryObject = getEntityManager().createQuery(queryString);
    if (params != null) {
        for (Map.Entry<String, Object> entry : params.entrySet())
            queryObject.setParameter(entry.getKey(), entry.getValue());
    }/*from   w  w  w.j  av  a  2  s. com*/
    if (start > -1)
        queryObject.setFirstResult(start);
    if (total > -1)
        queryObject.setMaxResults(total);
    return queryObject.getResultList();
}

From source file:org.eurekastreams.server.persistence.DomainEntityMapper.java

/**
 * Get a PagedSet of type V, built from the input query string, with the count determined by the input
 * countQueryString (more efficient than the version of this query without it).
 * //w ww .j a  v  a2s  .  c o  m
 * @param <V>
 *            the type of objects to return
 * @param from
 *            the starting index
 * @param to
 *            the ending index
 * @param queryString
 *            the query string
 * @param countQueryString
 *            the query string to use to determine the count - must return an integer
 * @param parameters
 *            the parameters to inject into the query string
 * @return a paged set of objects of type V as built from the input query string
 */
@SuppressWarnings("unchecked")
public <V> PagedSet<V> getTypedPagedResults(final int from, final int to, final String queryString,
        final String countQueryString, final HashMap<String, Object> parameters) {
    PagedSet<V> results = new PagedSet<V>();

    if (!results.isRangeValid(from, to)) {
        throw new IllegalArgumentException("from/to are invalid");
    }

    Query count = entityManager.createQuery(countQueryString);
    for (String key : parameters.keySet()) {
        count.setParameter(key, parameters.get(key));
    }

    long total;
    Object totalValue = count.getSingleResult();
    if (totalValue instanceof Long) {
        total = (Long) totalValue;
    } else {
        total = (Integer) totalValue;
    }

    // if no results, return empty set
    if (total == 0) {
        return results;
    }

    // return valid range even if you requested out of range
    int validTo = to;
    if (to >= total) {
        validTo = (int) total - 1;
    }

    // query to get the actual results
    Query select = entityManager.createQuery(queryString);
    for (String key : parameters.keySet()) {
        select.setParameter(key, parameters.get(key));
    }

    select.setFirstResult(from);
    select.setMaxResults(validTo - from + 1);

    ArrayList<V> resultList = (ArrayList<V>) select.getResultList();

    results.setFromIndex(from);
    results.setToIndex(validTo);
    results.setTotal((int) total);
    results.setPagedSet(resultList);

    return results;
}

From source file:au.com.optus.mcas.sdp.bizservice.ott.ordertracking.batchjob.dao.impl.AbstractDaoImpl.java

/**
 * {@inheritDoc}/*w  w w.  j a v a  2s. co m*/
 */
@SuppressWarnings("unchecked")
public List<E> findByNamedQueryAndNamedParams(final String queryName,
        final Map<String, ? extends Object> parameters, int limit) {
    if (getLogger().isDebugEnabled()) {
        getLogger().debug(String.format(
                "Finding instances of '%s' using named query '%s' and the following parameter/value(s): %s",
                getEntityClass(), queryName, parameters));
    }

    final Query namedQuery = getEntityManager().createNamedQuery(queryName);
    // final TypedQuery<E> namedQuery = mEntityManager.createNamedQuery(queryName, mEntityClass);
    if (!CollectionUtils.isEmpty(parameters)) {
        for (final Map.Entry<String, ? extends Object> param : parameters.entrySet()) {
            namedQuery.setParameter(param.getKey(), param.getValue());
        }
    }
    namedQuery.setFirstResult(0);
    namedQuery.setMaxResults(limit);

    return namedQuery.getResultList();
}

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

/**
 * Note: using SuppressWarnings annotation because the JPA API is not genericized.
 *///from   w  ww.jav a  2  s.  c  om
@SuppressWarnings(value = "unchecked")
public List<Relationship> getRelationships(Profile profile, int offset, int length) throws SocialSiteException {
    if (profile == null)
        throw new SocialSiteException("user is null");

    Query query = strategy.getNamedQuery("Relationship.getByProfileFrom");
    if (offset != 0)
        query.setFirstResult(offset);
    if (length != -1)
        query.setMaxResults(length);
    query.setParameter(1, profile);
    return (List<Relationship>) query.getResultList();
}

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

/**
 * Note: using SuppressWarnings annotation because the JPA API is not genericized.
 *///  w w  w . j  a  v a 2s. com
@SuppressWarnings(value = "unchecked")
public List<RelationshipRequest> getRelationshipRequestsByToProfile(Profile to, int offset, int length)
        throws SocialSiteException {
    if (to == null)
        throw new SocialSiteException("touser is null");
    Query query = strategy.getNamedQuery("RelationshipRequest.getByProfileTo");
    if (offset != 0)
        query.setFirstResult(offset);
    if (length != -1)
        query.setMaxResults(length);
    query.setParameter(1, to);
    return (List<RelationshipRequest>) query.getResultList();
}

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

/**
 * Note: using SuppressWarnings annotation because the JPA API is not genericized.
 */// w ww .j a v  a 2s  .  com
@SuppressWarnings(value = "unchecked")
public List<RelationshipRequest> getRelationshipRequestsByFromProfile(Profile from, int offset, int length)
        throws SocialSiteException {
    if (from == null)
        throw new SocialSiteException("profileFrom is null");
    Query query = strategy.getNamedQuery("RelationshipRequest.getByProfileFrom");
    if (offset != 0)
        query.setFirstResult(offset);
    if (length != -1)
        query.setMaxResults(length);
    query.setParameter(1, from);
    return (List<RelationshipRequest>) query.getResultList();
}

From source file:br.com.surittec.suricdi.core.repository.criteria.JPQL.java

private Query getQuery() {

    StringBuilder queryString = new StringBuilder();

    if (!select.isEmpty())
        append(queryString, "select", select, ",");
    append(queryString, "from", from);
    if (!where.isEmpty())
        append(queryString, "where", where, "and");
    if (!group.isEmpty())
        append(queryString, "group by", group, ",");
    if (!order.isEmpty())
        append(queryString, "order by", order, ",");

    Query query = entityManager.createQuery(queryString.toString());

    for (String paramName : params.keySet()) {
        query.setParameter(paramName, params.get(paramName));
    }/*  ww  w .  j a v  a2 s .  c  o m*/

    if (firstResult != null)
        query.setFirstResult(firstResult);
    if (maxResults != null)
        query.setMaxResults(maxResults);

    return query;
}

From source file:org.nuxeo.ecm.platform.audit.service.LogEntryProvider.java

@SuppressWarnings("unchecked")
public List<LogEntry> queryLogsByPage(String[] eventIds, Date limit, String[] categories, String path,
        int pageNb, int pageSize) {
    if (eventIds == null) {
        eventIds = new String[0];
    }//from  ww  w.j a v a2  s  .c  om
    if (categories == null) {
        categories = new String[0];
    }

    StringBuilder queryString = new StringBuilder();

    queryString.append("from LogEntry log where ");

    if (eventIds.length > 0) {
        String inClause = "(";
        for (String eventId : eventIds) {
            inClause += "'" + eventId + "',";
        }
        inClause = inClause.substring(0, inClause.length() - 1);
        inClause += ")";

        queryString.append(" log.eventId IN ").append(inClause);
        queryString.append(" AND ");
    }
    if (categories.length > 0) {
        String inClause = "(";
        for (String cat : categories) {
            inClause += "'" + cat + "',";
        }
        inClause = inClause.substring(0, inClause.length() - 1);
        inClause += ")";
        queryString.append(" log.category IN ").append(inClause);
        queryString.append(" AND ");
    }

    if (path != null && !"".equals(path.trim())) {
        queryString.append(" log.docPath LIKE '").append(path).append("%'");
        queryString.append(" AND ");
    }

    queryString.append(" log.eventDate >= :limit");
    queryString.append(" ORDER BY log.eventDate DESC");

    Query query = em.createQuery(queryString.toString());

    query.setParameter("limit", limit);

    if (pageNb > 1) {
        query.setFirstResult((pageNb - 1) * pageSize);
    }
    query.setMaxResults(pageSize);

    return doPublish(query.getResultList());
}

From source file:org.orcid.persistence.dao.impl.OrgDisambiguatedDaoImpl.java

@Override
public List<Pair<Long, Integer>> findDisambuguatedOrgsWithIncorrectPopularity(int maxResults) {
    Query query = entityManager
            .createNativeQuery("SELECT od1.id, actual.popularity FROM org_disambiguated od1 JOIN"
                    + " (SELECT od2.id id, COUNT(*) popularity FROM org_disambiguated od2 JOIN org o ON o.org_disambiguated_id = od2.id JOIN org_affiliation_relation oar ON oar.org_id = o.id GROUP BY od2.id)"
                    + " actual ON actual.id = od1.id WHERE od1.popularity <> actual.popularity");
    query.setMaxResults(maxResults);
    @SuppressWarnings("unchecked")
    List<Object[]> results = query.getResultList();
    List<Pair<Long, Integer>> pairs = new ArrayList<>();
    for (Object[] row : results) {
        Long id = ((BigInteger) row[0]).longValue();
        Integer popularity = ((BigInteger) row[1]).intValue();
        Pair<Long, Integer> pair = new ImmutablePair<Long, Integer>(id, popularity);
        pairs.add(pair);/*from  ww  w.j a  va 2  s. com*/
    }
    return pairs;
}

From source file:com.healthcit.cacure.dao.FormElementDao.java

/**
 * <b>questionId</b> is id of target item.
 * @param questionId Long/*w  w w .  ja va 2 s  . com*/
 * @param ordType ItemOrderingAction
 * @return pair of two consecutive Question items
 */
@SuppressWarnings("unchecked")
public List<FormElement> getAdjacentPairOfFormElements(Long elementId, ItemOrderingAction ordType) {
    String sign = (ordType == ItemOrderingAction.UP ? "<=" : ">=");
    String orderBy = (ordType == ItemOrderingAction.UP ? "DESC" : "ASC");
    String jpql = "select otherQst from FormElement ordQst, FormElement otherQst "
            + "where ordQst.id = :questionId " + "and otherQst.form.id = ordQst.form.id " + "and otherQst.ord "
            + sign + " ordQst.ord " + "order by otherQst.ord " + orderBy;

    Query query = em.createQuery(jpql);
    query.setParameter("questionId", elementId);
    query.setMaxResults(2);

    List<FormElement> elements = (List<FormElement>) query.getResultList();

    for (FormElement q : elements) {
        getElementsChildren(q);
    }
    return query.getResultList();
}