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:vlove.dao.impl.GenericDaoImpl.java

/**
 * @see vlove.dao.GenericDao#nativeQuery(String, Map, Integer)
 *///from w  w  w.j  a  va  2  s. com
@Override
public <T> List<T> nativeQuery(String query, Map<String, Object> parameters, Integer maxResults) {
    Query q = em.createNativeQuery(query);
    if (maxResults != null) {
        q.setMaxResults(maxResults);
    }
    applyParameters(q, parameters);
    return q.getResultList();
}

From source file:com.fantasy.stataggregator.entities.dao.AbstractRepository.java

protected T findLast() {
    javax.persistence.criteria.CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
    cq.select(cq.from(entityClass));//ww w .  j  a  va  2s.c  o  m
    javax.persistence.Query q = em.createQuery(cq);

    List<T> option = Optional.ofNullable(q.setMaxResults(1).getResultList()).orElse(new ArrayList());

    T entity = null;
    if (Objects.nonNull(option.get(0))) {
        entity = option.get(0);
    }
    return entity;
}

From source file:org.eurekastreams.server.persistence.mappers.stream.GetFlaggedActivitiesForOrganization.java

/**
 * Get all flagged activities posted directly under an organization.
 *
 * @param inRequest//w ww.j  av  a2s .c o m
 *            the request containing the organization and requesting user
 * @return a paged set of ActivityDTOs
 */
@Override
@SuppressWarnings("unchecked")
public PagedSet<ActivityDTO> execute(final GetFlaggedActivitiesByOrgRequest inRequest) {
    if (inRequest.getRequestingUserAccountId() == null) {
        log.error("Missing requesting user account.");
        throw new RuntimeException("Missing requesting user account.");
    }

    // get the total number of flagged activities
    Long flaggedActivityCount = (Long) buildQuery("count(*)", inRequest.getOrganizationId()).getSingleResult();

    List<ActivityDTO> activities;
    if (flaggedActivityCount > 0) {
        log.info("Found " + flaggedActivityCount
                + " flagged activity ids - passing them to the bulk activity mapper for ActivityDTOs.");

        Query q = buildQuery("id", inRequest.getOrganizationId());
        q.setFirstResult(inRequest.getStartIndex());
        q.setMaxResults(inRequest.getEndIndex() - inRequest.getStartIndex() + 1);
        List<Long> activityIds = q.getResultList();

        activities = activitiesMapper.execute(activityIds);
    } else {
        log.info("Found no flagged activity ids.");
        activities = new ArrayList<ActivityDTO>();
    }
    return new PagedSet<ActivityDTO>(inRequest.getStartIndex(), inRequest.getEndIndex(),
            flaggedActivityCount.intValue(), activities);
}

From source file:org.oscarehr.common.dao.ConsultResponseDao.java

@SuppressWarnings("unchecked")
public List<Object[]> search(ConsultationResponseSearchFilter filter) {
    String sql = this.getSearchQuery(filter, false);
    logger.debug("sql=" + sql);

    Query query = entityManager.createQuery(sql);
    query.setFirstResult(filter.getStartIndex());
    query.setMaxResults(filter.getNumToReturn());
    return query.getResultList();
}

From source file:org.ejbca.core.ejb.ra.UserData.java

/** @return return a List<UserData> with tokenType TOKEN_HARD_DEFAULT and status NEW or KEYRECOVERY. */
@SuppressWarnings("unchecked")
public static List<UserData> findNewOrKeyrecByHardTokenIssuerId(EntityManager entityManager,
        int hardTokenIssuerId, int maxResults) {
    final Query query = entityManager.createQuery(
            "SELECT a FROM UserData a WHERE a.hardTokenIssuerId=:hardTokenIssuerId AND a.tokenType>=:tokenType AND (a.status=:status1 OR a.status=:status2)");
    query.setParameter("hardTokenIssuerId", hardTokenIssuerId);
    query.setParameter("tokenType", SecConst.TOKEN_HARD_DEFAULT);
    query.setParameter("status1", EndEntityConstants.STATUS_NEW);
    query.setParameter("status2", EndEntityConstants.STATUS_KEYRECOVERY);
    if (maxResults > 0) {
        query.setMaxResults(maxResults);
    }/*from  www  . java  2s  .  co m*/
    return query.getResultList();
}

From source file:com.grummages.app.rest.entity.service.ListingAddonRESTFacade.java

private List<ListingAddon> find(boolean all, int maxResults, int firstResult) {
    try {/*w w  w .j  a  va 2s .  co  m*/
        Query query = entityManager.createQuery("SELECT object(o) FROM ListingAddon AS o");
        if (!all) {
            query.setMaxResults(maxResults);
            query.setFirstResult(firstResult);
        }
        return query.getResultList();
    } finally {
        entityManager.close();
    }
}

From source file:com.grummages.app.rest.entity.service.ListingPaymentRESTFacade.java

private List<ListingPayment> find(boolean all, int maxResults, int firstResult) {
    try {//from ww  w . jav a 2s. com
        Query query = entityManager.createQuery("SELECT object(o) FROM ListingPayment AS o");
        if (!all) {
            query.setMaxResults(maxResults);
            query.setFirstResult(firstResult);
        }
        return query.getResultList();
    } finally {
        entityManager.close();
    }
}

From source file:de.hska.ld.content.persistence.repository.custom.impl.DocumentRepositoryImpl.java

@Override
@Transactional/*from w ww  .jav  a 2 s  . c om*/
@SuppressWarnings("unchecked")
public Page<Document> searchDocumentByTitleOrDescription(String searchTerm, Pageable pageable) {

    FullTextEntityManager fullTextEntityManager = org.hibernate.search.jpa.Search.getFullTextEntityManager(em);

    // create native Lucene query unsing the query DSL
    // alternatively you can write the Lucene query using the Lucene query parser
    // or the Lucene programmatic API. The Hibernate Search DSL is recommended though
    QueryBuilder searchQb = fullTextEntityManager.getSearchFactory().buildQueryBuilder()
            .forEntity(Document.class).get();
    org.apache.lucene.search.Query luceneQuery = searchQb.phrase().onField("title").andField("description")
            //.onFields("title", "description")
            .sentence(searchTerm)
            //.matching(searchTerm)
            .createQuery();

    // wrap Lucene query in a javax.persistence.Query
    javax.persistence.Query jpaQuery = fullTextEntityManager.createFullTextQuery(luceneQuery, Document.class);

    long total = jpaQuery.getResultList().size();

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

    // execute search
    List result = jpaQuery.getResultList();

    return new PageImpl<Document>(result, pageable, total);
}

From source file:com.sapito.db.dao.AbstractDao.java

public List<T> findBySpecificField(String field, Object fieldContent, String predicates,
        LinkedHashMap<String, String> ordering, LinkedList<String> grouping) {
    CriteriaBuilder cb = entityManager.getCriteriaBuilder();
    CriteriaQuery cq = cb.createQuery();
    Root<T> root = cq.from(entityClass);
    Predicate predicate = null;/*from   www  .j a  v a2 s .  c o  m*/

    if (predicates.equals("equal")) {
        predicate = cb.equal(root.get(field), fieldContent);
    } else if (predicates.equals("likelower")) {
        predicate = cb.like(cb.lower(root.<String>get(field)), fieldContent.toString());
    } else if (predicates.equals("like")) {
        predicate = cb.like(root.<String>get(field), "%" + fieldContent.toString() + "%");
    }

    cq.select(root);
    cq.where(predicate);

    if (ordering != null) {
        Set<String> set = ordering.keySet();
        List<Order> orders = new ArrayList<>();
        for (String orderingField : set) {
            Order order;
            if (ordering.get(orderingField).equals("ASC")) {
                order = cb.asc(root.get(orderingField));
            } else {
                order = cb.desc(root.get(orderingField));
            }
            orders.add(order);
        }
        cq.orderBy(orders);
    }

    if (grouping != null) {
        Iterator iterator = grouping.iterator();
        List<Expression> groups = new LinkedList<>();
        while (iterator.hasNext()) {
            groups.add(root.get(iterator.next().toString()));
        }
        cq.groupBy(groups);
    }

    Query query = entityManager.createQuery(cq);
    query.setMaxResults(MAX_RECORDS_RETURNED);

    return query.getResultList();
}

From source file:me.doshou.admin.monitor.web.controller.JPAQLExecutorController.java

@PageableDefaults(pageNumber = 0, value = 10)
@RequestMapping(value = "/ql", method = RequestMethod.POST)
public String executeQL(final @RequestParam("ql") String ql, final Model model, final Pageable pageable) {

    model.addAttribute("sessionFactory", HibernateUtils.getSessionFactory(em));

    try {/* w  w w . j av a 2s  .co  m*/
        new TransactionTemplate(transactionManager).execute(new TransactionCallback<Void>() {
            @Override
            public Void doInTransaction(TransactionStatus status) {
                //1?ql
                try {
                    Query query = em.createQuery(ql);
                    int updateCount = query.executeUpdate();
                    model.addAttribute("updateCount", updateCount);
                    return null;
                } catch (Exception e) {
                }
                //2 ?ql
                String findQL = ql;
                String alias = QueryUtils.detectAlias(findQL);
                if (StringUtils.isEmpty(alias)) {
                    Pattern pattern = Pattern.compile("^(.*\\s*from\\s+)(.*)(\\s*.*)",
                            Pattern.MULTILINE | Pattern.CASE_INSENSITIVE);
                    findQL = pattern.matcher(findQL).replaceFirst("$1$2 o $3");
                }
                String countQL = QueryUtils.createCountQueryFor(findQL);
                Query countQuery = em.createQuery(countQL);
                Query findQuery = em.createQuery(findQL);
                findQuery.setFirstResult(pageable.getOffset());
                findQuery.setMaxResults(pageable.getPageSize());

                Page page = new PageImpl(findQuery.getResultList(), pageable,
                        (Long) countQuery.getSingleResult());

                model.addAttribute("resultPage", page);
                return null;
            }
        });
    } catch (Exception e) {
        StringWriter sw = new StringWriter();
        e.printStackTrace(new PrintWriter(sw));
        model.addAttribute(Constants.ERROR, sw.toString());
    }

    return showQLForm();
}