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.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));
    }/*  w w  w.j a  va 2s .c om*/

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

    return query;
}

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

/**
 * Note: using SuppressWarnings annotation because the JPA API is not genericized.
 *//*from   w  ww.j av  a 2s. c  o m*/
@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:org.easy.criteria.CriteriaProcessor.java

/**
 * @param query/*  ww w.j a v a2 s .co m*/
 * @param startIndex
 * @param maxResult
 */
private void setPagination(Query query, int startIndex, int maxResult) {
    // Pagination
    if (startIndex >= 0) {
        log.debug("startIndex = " + startIndex);
        query.setFirstResult(startIndex * maxResult);
    }

    if (maxResult > 0) {
        log.debug("maxResult = " + maxResult);
        query.setMaxResults(maxResult);
    }

}

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

/**
 * Note: using SuppressWarnings annotation because the JPA API is not genericized.
 *///from  www.j  av a 2  s. c om
@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.
 *///from   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:org.apache.roller.planet.business.jpa.JPAPlanetManagerImpl.java

public List getEntries(PlanetGroup group, Date startDate, Date endDate, int offset, int len)
        throws PlanetException {
    StringBuffer queryString = new StringBuffer();

    if (group == null) {
        throw new PlanetException("group cannot be null or empty");
    }//  w  ww.j a  v  a  2s.  c  o m

    List ret = null;
    try {
        long startTime = System.currentTimeMillis();

        StringBuffer sb = new StringBuffer();
        List params = new ArrayList();
        int size = 0;
        sb.append("SELECT e FROM SubscriptionEntry e ");
        sb.append("JOIN e.subscription.groups g ");

        params.add(size++, group.getHandle());
        sb.append("WHERE g.handle = ?").append(size);

        if (startDate != null) {
            params.add(size++, new Timestamp(startDate.getTime()));
            sb.append(" AND e.pubTime > ?").append(size);
        }
        if (endDate != null) {
            params.add(size++, new Timestamp(endDate.getTime()));
            sb.append(" AND e.pubTime < :?").append(size);
        }
        sb.append(" ORDER BY e.pubTime DESC");

        Query query = strategy.getDynamicQuery(sb.toString());
        for (int i = 0; i < params.size(); i++) {
            query.setParameter(i + 1, params.get(i));
        }
        if (offset > 0) {
            query.setFirstResult(offset);
        }
        if (len != -1) {
            query.setMaxResults(len);
        }

        ret = query.getResultList();

        long endTime = System.currentTimeMillis();

        log.debug("Generated aggregation of " + ret.size() + " in " + ((endTime - startTime) / 1000.0)
                + " seconds");

    } catch (Throwable e) {
        throw new PlanetException(e);
    }

    return ret;
}

From source file:org.apdplat.platform.dao.DaoSupport.java

/**
 * ??/*ww w . j  av a2  s  . c  o m*/
 * @param pageCriteria
 * @param query
 */
private void buildPageCriteria(PageCriteria pageCriteria, Query query) {
    if (query != null && pageCriteria != null) {
        int firstindex = (pageCriteria.getPage() - 1) * pageCriteria.getSize();
        int maxresult = pageCriteria.getSize();
        query.setFirstResult(firstindex).setMaxResults(maxresult);
    }
}

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];
    }/*ww w  .j  a  v  a  2 s.  co m*/
    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.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).
 * /*from w  ww  .  j  a va  2s  .  co 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:org.apache.ranger.common.RangerSearchUtil.java

public Query createSearchQuery(EntityManager em, String queryStr, String sortClause,
        SearchFilter searchCriteria, List<SearchField> searchFields, int objectClassType, boolean hasAttributes,
        boolean isCountQuery) {

    StringBuilder queryClause = buildWhereClause(searchCriteria, searchFields);

    super.addOrderByClause(queryClause, sortClause);

    Query query = em.createQuery(queryStr + queryClause);

    resolveQueryParams(query, searchCriteria, searchFields);

    if (!isCountQuery) {
        query.setFirstResult(searchCriteria.getStartIndex());
        updateQueryPageSize(query, searchCriteria);
    }/*  w w  w  . j a  va 2  s .c  o  m*/

    return query;
}