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:au.com.optus.mcas.sdp.bizservice.ott.ordertracking.batchjob.dao.impl.AbstractDaoImpl.java

/**
 * {@inheritDoc}//ww  w  . j a va  2  s.c o 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:org.eurekastreams.server.persistence.DomainEntityMapper.java

/**
 * Get a PagedSet of type V, built from the input query string.
 * //  www .j  a va 2  s .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 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 HashMap<String, Object> parameters) {
    PagedSet<V> results = new PagedSet<V>();

    log.debug("from: " + from + ", to: " + to);

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

    // TODO construct count query to avoid returning results of an entire
    // query just to get the count
    // like getPagedResults() does.
    // these didn't work:
    // "select count(q) from (select c.ideas from Campaign c where c.id=" +
    // containerId + ") q";
    // "select count(c.ideas) from Campaign c where c.id=id"

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

    int total = count.getResultList().size();

    // 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) {
        log.debug("to>=total - to: " + to + ", total: " + total);
        validTo = total - 1;
    }
    log.debug("Query: " + queryString + ", total: " + total + ", validTo: " + validTo);

    // 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);
    int maxResults = validTo - from + 1;
    if (maxResults <= 0) {
        log.debug("Maxresults would have been negative or zero - "
                + "most likely an error on the client - returning no records");
        return results;
    }
    select.setMaxResults(maxResults);

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

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

    return results;
}

From source file:org.sakaiproject.kernel.site.SiteServiceImpl.java

/**
 * {@inheritDoc}/*  w  w  w.ja v  a2  s. c  o  m*/
 *
 * @see org.sakaiproject.kernel.api.site.SiteService#getSiteById(java.lang.String)
 */
public SiteBean getSiteById(String siteId) {
    Query findById = entityManager.createNamedQuery(SiteIndexBean.Queries.FINDBY_ID);
    LOG.info("Searching for Site ID [" + siteId + "]");
    findById.setParameter(SiteIndexBean.QueryParams.FINDBY_ID_ID, siteId);
    findById.setFirstResult(0);
    findById.setMaxResults(1);
    List<?> results = findById.getResultList();
    if (results.size() > 0) {
        SiteIndexBean index = (SiteIndexBean) results.get(0);
        String sitePath = index.getRef();
        LOG.info("Found Site " + siteId + " at " + sitePath);
        return getSite(sitePath);
    }
    return null;
}

From source file:org.kuali.rice.krad.data.jpa.JpaQueryTranslator.java

@Override
public void convertQueryFlags(org.kuali.rice.core.api.criteria.QueryByCriteria qbc, Query query) {
    //ojb's is 1 based, our query api is zero based
    //final int startAtIndex = criteria.getStartAtIndex() != null ? criteria.getStartAtIndex() + 1 : 1;
    // XXX: FIXME: had to change this to 0...why was this setting start index to 1?
    // experimentation shows that initial offset of 1 is required for OJB criteria tests to pass
    final int startAtIndex = qbc.getStartAtIndex() != null ? qbc.getStartAtIndex() : 0;
    query.setFirstResult(startAtIndex);

    if (qbc.getMaxResults() != null) {
        //not subtracting one from MaxResults in order to retrieve
        //one extra row so that the MoreResultsAvailable field can be set
        query.setMaxResults(qbc.getMaxResults());
    }//from   w  w w .j av a2 s. c  o m
}

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

public List<?> nativeQuery(String queryString, Map<String, Object> params, int pageNb, int pageSize) {
    if (pageSize <= 0) {
        pageSize = 1000;/*from  w w w . ja v  a2s.  c o  m*/
    }
    Query query = em.createQuery(queryString);
    for (Entry<String, Object> en : params.entrySet()) {
        query.setParameter(en.getKey(), en.getValue());
    }
    if (pageNb > 1) {
        query.setFirstResult((pageNb - 1) * pageSize);
    }
    query.setMaxResults(pageSize);
    return doPublishIfEntries(query.getResultList());
}

From source file:org.apache.cxf.fediz.service.idp.service.jpa.IdpDAOJPAImpl.java

@Override
public List<Idp> getIdps(int start, int size, List<String> expandList) {
    List<Idp> list = new ArrayList<Idp>();

    Query query = null;
    query = em.createQuery("select i from IDP i");

    /*List serviceEntities = query.setFirstResult(start)
    .setMaxResults(size)/*from   w  ww .  j a v a 2 s  .  c o  m*/
    .getResultList();*/

    //@SuppressWarnings("rawtypes")
    List idpEntities = query.setFirstResult(start).setMaxResults(size).getResultList();

    for (Object obj : idpEntities) {
        IdpEntity entity = (IdpEntity) obj;
        list.add(entity2domain(entity, expandList));
    }
    return list;
}

From source file:org.apache.syncope.core.persistence.dao.impl.UserDAOImpl.java

@Override
public final List<SyncopeUser> findAll(final Set<Long> adminRoles, final int page, final int itemsPerPage) {

    final Query query = entityManager.createNativeQuery(getFindAllQuery(adminRoles).toString());

    query.setFirstResult(itemsPerPage * (page <= 0 ? 0 : page - 1));

    if (itemsPerPage > 0) {
        query.setMaxResults(itemsPerPage);
    }/*from w  ww.j a  va2s .  c  o  m*/

    List<Number> userIds = new ArrayList<Number>();
    List resultList = query.getResultList();

    //fix for HHH-5902 - bug hibernate
    if (resultList != null) {
        for (Object userId : resultList) {
            if (userId instanceof Object[]) {
                userIds.add((Number) ((Object[]) userId)[0]);
            } else {
                userIds.add((Number) userId);
            }
        }
    }

    List<SyncopeUser> result = new ArrayList<SyncopeUser>(userIds.size());

    SyncopeUser user;
    for (Object userId : userIds) {
        user = find(((Number) userId).longValue());
        if (user == null) {
            LOG.error("Could not find user with id {}, " + "even though returned by the native query", userId);
        } else {
            result.add(user);
        }
    }

    return result;
}

From source file:net.kamhon.ieagle.dao.Jpa2Dao.java

@SuppressWarnings("unchecked")
public List<T> findBlock(String query, final int offset, final int recordCount, final Object... objectArray) {
    final String query2 = convertJpaPositionParams(query);
    Query q = em.createQuery(query2);
    for (int i = 0; i < objectArray.length; i++) {
        q.setParameter(i + 1, objectArray[i]);
    }//from   w w w .java  2s  .co  m
    q.setFirstResult(offset);
    q.setMaxResults(recordCount);
    return q.getResultList();
}

From source file:com.impetus.kundera.rest.common.EntityUtils.java

/**
 * @param queryString/*  w w w .j  a  va  2  s . com*/
 * @param q
 */
public static void setQueryParameters(String queryString, HashMap<String, String> paramsMap, Query q) {
    KunderaQuery kq = ((QueryImpl) q).getKunderaQuery();
    Set<Parameter<?>> parameters = kq.getParameters();
    for (String paramName : paramsMap.keySet()) {
        String value = paramsMap.get(paramName);

        if (StringUtils.isNumeric(paramName)) {
            for (Parameter param : parameters) {
                if (param.getPosition() == Integer.parseInt(paramName)) {
                    Class<?> paramClass = param.getParameterType();
                    PropertyAccessor accessor = PropertyAccessorFactory.getPropertyAccessor(paramClass);
                    Object paramValue = accessor.fromString(paramClass, value);
                    q.setParameter(Integer.parseInt(paramName), paramValue);
                    break;
                }
            }
        } else {
            for (Parameter param : parameters) {
                if (param.getName().equals(paramName)) {
                    Class<?> paramClass = param.getParameterType();
                    PropertyAccessor accessor = PropertyAccessorFactory.getPropertyAccessor(paramClass);
                    Object paramValue = accessor.fromString(paramClass, value);
                    if (paramName.equalsIgnoreCase("firstResult")) {
                        q.setFirstResult(Integer.parseInt((String) paramValue));
                    } else if (paramName.equalsIgnoreCase("maxResult")) {
                        q.setMaxResults(Integer.parseInt((String) paramValue));
                    } else {
                        q.setParameter(paramName, paramValue);
                    }
                    break;
                }
            }

        }
    }
}

From source file:net.kamhon.ieagle.dao.JpaDao.java

@SuppressWarnings("unchecked")
@Override/*from  w ww.  j a v  a2  s  .c  om*/
public List<T> findBlock(String query, final int offset, final int recordCount, final Object... objectArray) {
    final String query2 = convertJpaPositionParams(query);
    return getJpaTemplate().executeFind(new JpaCallback<List<T>>() {
        @Override
        public List<T> doInJpa(EntityManager em) throws PersistenceException {
            Query q = em.createQuery(query2);
            for (int i = 0; i < objectArray.length; i++) {
                q.setParameter(i + 1, objectArray[i]);
            }
            q.setFirstResult(offset);
            q.setMaxResults(recordCount);
            return q.getResultList();
        }
    });
}