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:gr.upatras.ece.nam.baker.impl.BakerJpaController.java

@SuppressWarnings("unchecked")
public List<ApplicationMetadata> readAppsMetadataForOwnerID(Long ownerid, int firstResult, int maxResults) {
    EntityManager entityManager = entityManagerFactory.createEntityManager();
    //Query q = entityManager.createQuery("SELECT m FROM BunMetadata m");
    Query q;

    if ((ownerid != null) && (ownerid >= 0))
        q = entityManager.createQuery(/*  w w  w .  j a v a 2  s  .c om*/
                "SELECT a FROM ApplicationMetadata a WHERE a.owner.id=" + ownerid + " ORDER BY a.id");
    else
        q = entityManager.createQuery("SELECT a FROM ApplicationMetadata a ORDER BY a.id");

    q.setFirstResult(firstResult);
    q.setMaxResults(maxResults);
    return q.getResultList();
}

From source file:gr.upatras.ece.nam.baker.impl.BakerJpaController.java

public List<ApplicationMetadata> readAppsMetadata(Long categoryid, int firstResult, int maxResults) {
    EntityManager entityManager = entityManagerFactory.createEntityManager();
    Query q;

    if ((categoryid != null) && (categoryid >= 0))
        q = entityManager.createQuery(/*www . jav a2 s  .co  m*/
                "SELECT a FROM ApplicationMetadata a WHERE a.categories.id=" + categoryid + " ORDER BY a.id");
    else
        q = entityManager.createQuery("SELECT a FROM ApplicationMetadata a ORDER BY a.id");
    q.setFirstResult(firstResult);
    q.setMaxResults(maxResults);
    return q.getResultList();
}

From source file:corner.orm.gae.impl.PaginatedJapEntityService.java

License:asdf

/**
* 
* magic paginate method./*from w ww  .j av a 2  s. c  om*/
* eg:
* <code>
*  options.setPage(2);
*
*
*  paginate(Member.class,new Object[]{"email=?","asdf@asdf.net"},"userName desc",options)
        
*  paginate(Member.class,"email='asdf@asdf.net'","userName desc",options)
*
*  List conditions = new ArrayList();
*  conditions.add("userName=? and password=?");
*  conditions.add(userName);
*  conditions.add(password);
*  paginate(Member.class,conditions,"userName desc",options)
* 
* </code>
* Magic conditions query criteria
* @param persistClass persistence class
* @param conditions query criteria
* @param order order by sql
* @param options pagination options.
* @return include result and totalRecord.
*/
public PaginationList paginate(final Class<?> persistClass, final Object conditions, final String order,
        final PaginationOptions options) {
    final Iterable con = typeCoercer.coerce(conditions, Iterable.class);

    return (PaginationList) this.template.execute(new JpaCallback() {
        @Override
        public Object doInJpa(EntityManager entityManager) throws PersistenceException {

            final Iterator it = con == null ? null : con.iterator();

            String conditionJPQL = buildConditionJPQL(persistClass, it).toString();

            //query list
            final StringBuffer queryJPQL = new StringBuffer(conditionJPQL);
            appendOrder(queryJPQL, order);
            queryJPQL.insert(0, "select root." + EntityConstants.ID_PROPERTY_NAME);
            Query query = entityManager.createQuery(queryJPQL.toString());

            //count query
            final StringBuffer countJPQL = new StringBuffer(conditionJPQL);
            countJPQL.insert(0, "select count(root) ");
            Query countQuery = entityManager.createQuery(countJPQL.toString());

            if (it != null) {
                int i = 0;
                while (it.hasNext()) {
                    i++;
                    Object obj = it.next();
                    query.setParameter(String.valueOf(i), obj);
                    countQuery.setParameter(String.valueOf(i), obj);
                }
            }
            //get perpage
            int perPage = options.getPerPage();
            int page = options.getPage();
            if (page < 1) {
                page = 1;
            }
            query.setFirstResult((page - 1) * perPage);
            query.setMaxResults(perPage);
            PaginationList list = new PaginationList(query.getResultList().iterator(), options);

            //query total record number
            //beacause jpa rowCount is integer type.so convert as long
            options.setTotalRecord(Long.parseLong(countQuery.getSingleResult().toString()));
            return list;
        }
    });
}

From source file:gov.utah.dts.det.ccl.dao.impl.FacilityDaoImpl.java

@Override
public List<FacilitySearchView> searchFacilities(FacilitySearchCriteria criteria, SortBy sortBy, int page,
        int resultsPerPage) {
    StringBuilder sb = new StringBuilder(FACILITY_SEARCH_QUERY);
    buildSearchQueryString(sb, criteria, sortBy);

    Query query = buildSearchQuery(sb.toString(), criteria);

    int maxResults = resultsPerPage == 0 ? 250 : resultsPerPage;
    int firstResult = page * resultsPerPage;
    query.setFirstResult(firstResult);/*from   w  w  w .java2  s . c  om*/
    query.setMaxResults(maxResults);

    List<FacilitySearchView> facilities = query.getResultList();
    for (FacilitySearchView f : facilities) {
        f.getLicenses().size();
    }

    return facilities;
}

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

/**
 * Finds ORCID Ids by ProfileEventTypes/* w  w w.ja  v a  2 s  .  c o  m*/
 * 
 * @param maxResults
 *            Maximum number of results returned.
 * 
 * @param pets
 *            A list of ProfileEventTypes.
 * 
 * @param not
 *            If false ORCIDs returned ARE associated with one of the
 *            ProfileEventTypes If true ORCIDs returned ARE NOT associated
 *            with one of the ProfileEventTypes
 * 
 * @param orcidsToExclude
 *            ORCID Ids to be excluded from reuturned results
 * 
 * @return list of ORCID Ids as a list of strings
 */
@SuppressWarnings("unchecked")
@Override
public List<String> findByMissingEventTypes(int maxResults, List<ProfileEventType> pets,
        Collection<String> orcidsToExclude, boolean not) {
    /*
     * builder produces a query that will look like the following
     * 
     * select p.orcid from profile p left join profile_event pe on pe.orcid
     * = p.orcid and
     * (pe.profile_event_type0='EMAIL_VERIFY_CROSSREF_MARKETING_CHECK' or
     * pe.profile_event_type0='EMAIL_VERIFY_CROSSREF_MARKETING_FAIL') where
     * pe.orcid is null limit 1000;
     */
    StringBuilder builder = new StringBuilder();

    builder.append("select p.orcid from profile p left join profile_event pe on pe.orcid = p.orcid and ");

    // builder.append("in (select pe.orcid from profile_event as pe where ");
    builder.append("(");
    for (int i = 0; i < pets.size(); i++) {
        if (i != 0)
            builder.append("or ");
        builder.append("pe.profile_event_type=:profileEventType");
        builder.append(Integer.toString(i));
        builder.append(" ");
    }
    builder.append(")");
    builder.append("where pe.orcid is ");
    if (!not)
        builder.append("not ");
    builder.append("null ");

    if (orcidsToExclude != null && !orcidsToExclude.isEmpty()) {
        builder.append(" AND p.orcid NOT IN :orcidsToExclude");
    }

    Query query = entityManager.createNativeQuery(builder.toString());

    for (int i = 0; i < pets.size(); i++) {
        query.setParameter("profileEventType" + i, pets.get(i).name());
    }

    if (orcidsToExclude != null && !orcidsToExclude.isEmpty()) {
        query.setParameter("orcidsToExclude", orcidsToExclude);
    }
    query.setMaxResults(maxResults);
    return query.getResultList();
}

From source file:gov.utah.dts.det.ccl.dao.impl.FacilityDaoImpl.java

@Override
public List<FacilityResultView> searchFacilitiesByName(String name, Long excludeFacilityId) {
    StringBuilder sb = new StringBuilder(FACILITY_NAME_SEARCH_QUERY);
    if (excludeFacilityId != null) {
        sb.append(FACILITY_NAME_SEARCH_EXCLUDE_CLAUSE);
    }/*w ww.j av  a2s  .c om*/
    sb.append(FACILITY_NAME_SEARCH_ORDER_BY);

    Query query = em.createQuery(sb.toString());
    query.setParameter("facilityName", name.toUpperCase() + "%");
    if (excludeFacilityId != null) {
        query.setParameter("excludeFacilityId", excludeFacilityId);
    }
    query.setMaxResults(20);
    List<FacilityResultView> frvs = query.getResultList();
    return frvs;
}

From source file:org.opentides.dao.impl.BaseEntityDaoJpaImpl.java

/**
 * {@inheritDoc}//from w ww . j  av  a  2  s  . c o m
 */
@Override
@SuppressWarnings("unchecked")
public final List<T> 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()) {
            if (entry.getKey() != null && entry.getKey().startsWith("hint.")) {
                queryObject.setHint(entry.getKey().substring(5), entry.getValue());
            } else {
                queryObject.setParameter(entry.getKey(), entry.getValue());
            }
        }
    }
    if (start > -1)
        queryObject.setFirstResult(start);
    if (total > -1)
        queryObject.setMaxResults(total);
    return queryObject.getResultList();
}

From source file:org.cgiar.dapa.ccafs.tpe.dao.impl.PhenologyGrowthDao.java

private List<Float> getOutliers(Float lowerLimit, Float upperLimit, Integer country, Integer cultivar,
        String year, Integer env) {
    StringBuffer q = new StringBuffer("select r.wrr14 from " + entityClass.getName())
            .append(" r where r.region.id =:country").append(" or r.region.parent.parent.id =:country")
            .append(" and r.cultivar.id =:cultivar").append(" and r.environment.id =:environment")
            .append(" and r.year =:year").append(" and r.wrr14 <:lower").append(" or r.wrr14 >:upper")
            .append(" order by r.wrr14 asc");

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

    query.setParameter("country", country);
    query.setParameter("cultivar", cultivar);
    query.setParameter("year", year);
    query.setParameter("environment", env);
    query.setParameter("lower", lowerLimit);
    query.setParameter("upper", upperLimit);

    query.setFirstResult(0);//from  ww w  .j a va2s .com
    query.setMaxResults(4);

    List<Float> results = query.getResultList();

    return results;

}

From source file:com.haulmont.cuba.core.app.RdbmsStore.java

protected Query createQuery(EntityManager em, LoadContext context, boolean singleResult) {
    LoadContext.Query contextQuery = context.getQuery();
    if ((contextQuery == null || isBlank(contextQuery.getQueryString())) && context.getId() == null)
        throw new IllegalArgumentException("Query string or ID needed");

    DataServiceQueryBuilder queryBuilder = AppBeans.get(DataServiceQueryBuilder.NAME);
    queryBuilder.init(contextQuery == null ? null : contextQuery.getQueryString(),
            contextQuery == null ? null : contextQuery.getParameters(), context.getId(),
            context.getMetaClass());/*from w w  w . jav  a 2s .  co  m*/

    queryBuilder.setSingleResult(singleResult);

    if (!context.getPrevQueries().isEmpty()) {
        log.debug("Restrict query by previous results");
        queryBuilder.restrictByPreviousResults(userSessionSource.getUserSession().getId(),
                context.getQueryKey());
    }
    Query query = queryBuilder.getQuery(em);

    if (contextQuery != null) {
        if (contextQuery.getFirstResult() != 0)
            query.setFirstResult(contextQuery.getFirstResult());
        if (contextQuery.getMaxResults() != 0)
            query.setMaxResults(contextQuery.getMaxResults());
        if (contextQuery.isCacheable()) {
            query.setCacheable(contextQuery.isCacheable());
        }
    }

    return query;
}

From source file:com.haulmont.cuba.core.app.RdbmsStore.java

@Override
public List<KeyValueEntity> loadValues(ValueLoadContext context) {
    Preconditions.checkNotNullArgument(context, "context is null");
    Preconditions.checkNotNullArgument(context.getQuery(), "query is null");

    ValueLoadContext.Query contextQuery = context.getQuery();

    if (log.isDebugEnabled())
        log.debug("query: " + (DataServiceQueryBuilder.printQuery(contextQuery.getQueryString()))
                + (contextQuery.getFirstResult() == 0 ? "" : ", first=" + contextQuery.getFirstResult())
                + (contextQuery.getMaxResults() == 0 ? "" : ", max=" + contextQuery.getMaxResults()));

    QueryParser queryParser = queryTransformerFactory.parser(contextQuery.getQueryString());
    if (!checkValueQueryPermissions(queryParser)) {
        return Collections.emptyList();
    }//  ww w  .  j a v a  2s  .c o  m

    List<KeyValueEntity> entities = new ArrayList<>();

    try (Transaction tx = createLoadTransaction()) {
        EntityManager em = persistence.getEntityManager(storeName);
        em.setSoftDeletion(context.isSoftDeletion());

        List<String> keys = context.getProperties();

        DataServiceQueryBuilder queryBuilder = AppBeans.get(DataServiceQueryBuilder.NAME);
        queryBuilder.init(contextQuery.getQueryString(), contextQuery.getParameters(), null,
                metadata.getClassNN(KeyValueEntity.class).getName());
        Query query = queryBuilder.getQuery(em);

        if (contextQuery.getFirstResult() != 0)
            query.setFirstResult(contextQuery.getFirstResult());
        if (contextQuery.getMaxResults() != 0)
            query.setMaxResults(contextQuery.getMaxResults());

        List resultList = query.getResultList();
        List<Integer> notPermittedSelectIndexes = getNotPermittedSelectIndexes(queryParser);
        for (Object item : resultList) {
            KeyValueEntity entity = new KeyValueEntity();
            entity.setIdName(context.getIdName());
            entities.add(entity);

            if (item instanceof Object[]) {
                Object[] row = (Object[]) item;
                for (int i = 0; i < keys.size(); i++) {
                    String key = keys.get(i);
                    if (row.length > i) {
                        if (notPermittedSelectIndexes.contains(i)) {
                            entity.setValue(key, null);
                        } else {
                            entity.setValue(key, row[i]);
                        }
                    }
                }
            } else if (!keys.isEmpty()) {
                if (!notPermittedSelectIndexes.isEmpty()) {
                    entity.setValue(keys.get(0), null);
                } else {
                    entity.setValue(keys.get(0), item);
                }
            }
        }

        tx.commit();
    }

    return entities;
}