Example usage for javax.persistence TypedQuery setMaxResults

List of usage examples for javax.persistence TypedQuery setMaxResults

Introduction

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

Prototype

TypedQuery<X> setMaxResults(int maxResult);

Source Link

Document

Set the maximum number of results to retrieve.

Usage

From source file:org.synyx.hades.dao.orm.GenericJpaDao.java

/**
 * @param query/*from   w  ww.j a v  a  2s  . c o  m*/
 * @param spec
 * @param pageable
 * @return
 */
private Page<T> readPage(final TypedQuery<T> query, final Pageable pageable, final Specification<T> spec) {

    query.setFirstResult(pageable.getFirstItem());
    query.setMaxResults(pageable.getPageSize());

    return new PageImpl<T>(query.getResultList(), pageable, count(spec));
}

From source file:edu.sabanciuniv.sentilab.sare.controllers.entitymanagers.LexiconBuilderController.java

/**
 * Finds the builder associated with a given corpus and lexicon.
 * @param em the {@link EntityManager} to use.
 * @param corpus the {@link DocumentCorpus} being used to build the lexicon.
 * @param lexicon the {@link Lexicon} being built.
 * @return the {@link LexiconBuilderDocumentStore} object found, if any; {@code null} otherwise.
 *//*  w  w w .ja  v a  2 s  . c  o m*/
public LexiconBuilderDocumentStore findBuilder(EntityManager em, DocumentCorpus corpus, Lexicon lexicon) {
    Validate.notNull(em, CannedMessages.NULL_ARGUMENT, "em");
    Validate.notNull(corpus, CannedMessages.NULL_ARGUMENT, "corpus");
    Validate.notNull(lexicon, CannedMessages.NULL_ARGUMENT, "lexicon");

    TypedQuery<LexiconBuilderDocumentStore> query = em.createQuery(
            "SELECT b FROM LexiconBuilderDocumentStore b "
                    + "WHERE b.baseStore=:corpus AND :lexicon MEMBER OF b.referencedObjects",
            LexiconBuilderDocumentStore.class);
    query.setMaxResults(1).setParameter("corpus", corpus).setParameter("lexicon", lexicon);

    return this.getSingleResult(query);
}

From source file:eu.europa.ec.fisheries.uvms.exchange.dao.bean.ExchangeLogDaoBean.java

@Override
public List<ExchangeLog> getExchangeLogListPaginated(Integer page, Integer listSize, String sql,
        List<SearchValue> searchKeyValues) throws ExchangeDaoException {
    try {//from   w  w w . j  av a 2  s. co m
        LOG.debug("SQL QUERY IN LIST PAGINATED: " + sql);
        TypedQuery<ExchangeLog> query = em.createQuery(sql, ExchangeLog.class);

        HashMap<ExchangeSearchField, List<SearchValue>> orderedValues = SearchFieldMapper
                .combineSearchFields(searchKeyValues);

        setQueryParameters(query, orderedValues);

        query.setFirstResult(listSize * (page - 1));
        query.setMaxResults(listSize);

        return query.getResultList();
    } catch (IllegalArgumentException e) {
        LOG.error("[ Error getting exchangelog list paginated ] {}", e.getMessage());
        throw new ExchangeDaoException("[ Error when getting list ] ");
    } catch (Exception e) {
        LOG.error("[ Error getting exchangelog list paginated ]  {}", e.getMessage());
        throw new ExchangeDaoException("[ Error when getting list ] ");
    }
}

From source file:bzzAgent.BiteSizedBzzDaoJpa.java

@Override
public List<BsbAgentActivityEntity> getBsbAgentActivities(BsbAgentActivitySearchParams params) {
    Validate.notBlank(params.getUsername(), "username was missing");
    Validate.isTrue(params.getStatusList().size() > 0, "no statuses were passed");

    final String orderString;
    final String sortOrder = params.getSortorder().toString();
    switch (params.getOrderby()) {
    case lastmodified:
        orderString = " bsbaae.lastModified " + sortOrder;
        break;/*from w w  w. j a v  a  2 s.c o m*/
    case priority:
        if (params.getSortorder() == SortOrder.asc) {
            orderString = " bsbaae.clientSponsored asc, bsbaae.endDate desc";
        } else {
            orderString = " bsbaae.clientSponsored desc, bsbaae.endDate asc";
        }
        break;
    default:
        throw new RuntimeException(
                "unhandled case for BsbAgentActivitySearchParams.orderBy=" + params.getOrderby());
    }
    final List<Integer> statusList = new ArrayList<>();
    for (BsbActivityStatus bsbActivityStatus : params.getStatusList()) {
        final CampaignInviteStatus campaignInviteStatus = BsbActivityStatus
                .toCampaignInviteStatus(bsbActivityStatus);
        if (campaignInviteStatus != null) {
            statusList.add(campaignInviteStatus.getValue());
        }
    }

    final LocalDate today = LocalDate.now();
    final StringBuilder sql = new StringBuilder("from BsbAgentActivityEntity bsbaae ")
            .append(" left join fetch bsbaae.incentives incentive ")
            .append(" left join fetch bsbaae.ecommerceRetailers ecommerceRetailers ")
            .append(" where bsbaae.username = :username ")
            .append(" and bsbaae.campaignInviteStatus in :statusList")
            .append(" and bsbaae.startDate <= :today and bsbaae.endDate >= :today").append(" order by ")
            .append(orderString);

    final TypedQuery<BsbAgentActivityEntity> query2 = em
            .createQuery(sql.toString(), BsbAgentActivityEntity.class)
            .setParameter("username", params.getUsername()).setParameter("today", today)
            .setParameter("statusList", statusList);
    if (params.getLimit() != null && params.getLimit() > 0) {
        query2.setMaxResults(params.getLimit());
    }
    return query2.getResultList();
}

From source file:net.awired.generic.jpa.dao.impl.GenericDaoImpl.java

/**
 * @param length// www.  j  a v a 2  s.c  o m
 *            maxResult
 * @param start
 *            pagination starting point
 * @param search
 *            search string like ' name: toto , dupont' to search for %toto% on name + %dupont% in all properties
 * @param searchProperties
 *            properties to search or all if null
 * @param orders
 *            sorted result by properties
 * @return
 */
public List<ENTITY> findFiltered(Integer length, Integer start, String search, List<String> searchProperties,
        List<Order> orders) {
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<ENTITY> query = builder.createQuery(entityClass);
    Root<ENTITY> root = query.from(entityClass);

    if (!Strings.isNullOrEmpty(search)) {
        Predicate[] buildFilterPredicates = BuildFilterPredicates(root, search, searchProperties);
        if (buildFilterPredicates.length > 0) {
            query.where(builder.or(buildFilterPredicates));
        }
    }

    if (orders != null) {
        query.orderBy(OrderToOrder.toJpa(builder, root, orders));
    }

    TypedQuery<ENTITY> q = entityManager.createQuery(query);
    if (start != null) {
        q.setFirstResult(start);
    }
    if (length != null) {
        q.setMaxResults(length);
    }
    return findList(q);
}

From source file:com.music.dao.PieceDao.java

@SuppressWarnings("rawtypes")
public Map<Piece, Integer> getTopRecentPieces(int page, int pageSize, DateTime minusWeeks) {
    TypedQuery<List> query = getEntityManager().createQuery(
            "SELECT new list(ev.piece, COUNT(ev) AS cnt) FROM PieceEvaluation ev WHERE ev.dateTime > :threshold AND ev.piece.likes > 0 GROUP BY ev.piece ORDER BY cnt DESC, ev.dateTime DESC",
            List.class);
    query.setParameter("threshold", minusWeeks);
    query.setFirstResult(page * pageSize);
    query.setMaxResults(pageSize);

    Map<Piece, Integer> result = new LinkedHashMap<>();
    for (List<?> list : query.getResultList()) {
        result.put((Piece) list.get(0), ((Long) list.get(1)).intValue());
    }/*w ww  .j a va  2s  .  c  o m*/
    return result;
}

From source file:com.ushahidi.swiftriver.core.api.dao.impl.JpaBucketDao.java

public List<Bucket> findAll(String searchTerm, int count, int page) {
    String qlString = "SELECT b FROM Bucket b WHERE " + "b.published = 1 "
            + "AND (b.name LIKE :term OR b.description LIKE :term " + "OR b.bucketNameCanonical LIKE :term)";

    TypedQuery<Bucket> query = em.createQuery(qlString, Bucket.class);
    query.setParameter("term", "%" + searchTerm + "%");
    query.setMaxResults(count);
    query.setFirstResult(count * (page - 1));

    return query.getResultList();
}

From source file:com.sishuok.es.common.repository.support.SimpleBaseRepository.java

/**
 * Reads the given {@link javax.persistence.TypedQuery} into a {@link org.springframework.data.domain.Page} applying the given {@link org.springframework.data.domain.Pageable} and
 * {@link org.springframework.data.jpa.domain.Specification}.
 *
 * @param query    must not be {@literal null}.
 * @param spec     can be {@literal null}.
 * @param pageable can be {@literal null}.
 * @return//from   www .j av  a2s . c  o  m
 */
private Page<M> readPage(TypedQuery<M> query, Pageable pageable, Specification<M> spec) {

    query.setFirstResult(pageable.getOffset());
    query.setMaxResults(pageable.getPageSize());

    Long total = QueryUtils.executeCountQuery(getCountQuery(spec));
    List<M> content = total > pageable.getOffset() ? query.getResultList() : Collections.<M>emptyList();

    return new PageImpl<M>(content, pageable, total);
}

From source file:com.luna.common.repository.support.SimpleBaseRepository.java

/**
 * Reads the given {@link javax.persistence.TypedQuery} into a {@link org.springframework.data.domain.Page} applying the given {@link org.springframework.data.domain.Pageable} and
 * {@link org.springframework.data.jpa.domain.Specification}.
 *
 * @param query    must not be {@literal null}.
 * @param spec     can be {@literal null}.
 * @param pageable can be {@literal null}.
 * @return//from  w  ww.  ja v  a  2s.co  m
 */
protected Page<M> readPage(TypedQuery<M> query, Pageable pageable, Specification<M> spec) {

    query.setFirstResult(pageable.getOffset());
    query.setMaxResults(pageable.getPageSize());

    Long total = QueryUtils.executeCountQuery(getCountQuery(spec));
    List<M> content = total > pageable.getOffset() ? query.getResultList() : Collections.<M>emptyList();

    return new PageImpl<M>(content, pageable, total);
}

From source file:cn.guoyukun.spring.jpa.repository.support.SimpleBaseRepository.java

/**
 * Reads the given {@link javax.persistence.TypedQuery} into a {@link org.springframework.data.domain.Page} applying the given {@link org.springframework.data.domain.Pageable} and
 * {@link org.springframework.data.jpa.domain.Specification}.
 *
 * @param query    must not be {@literal null}.
 * @param spec     can be {@literal null}.
 * @param pageable can be {@literal null}.
 * @return/*from w  w w .  j  a  v a 2 s .c  om*/
 */
@Override
protected Page<M> readPage(TypedQuery<M> query, Pageable pageable, Specification<M> spec) {

    query.setFirstResult(pageable.getOffset());
    query.setMaxResults(pageable.getPageSize());

    Long total = QueryUtils.executeCountQuery(getCountQuery(spec));
    List<M> content = total > pageable.getOffset() ? query.getResultList() : Collections.<M>emptyList();

    return new PageImpl4jqgrid<M>(content, pageable, total);
}