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:org.orcid.persistence.dao.impl.ProfileDaoImpl.java

@SuppressWarnings("unchecked")
@Override//from   w  ww. j a  v  a 2 s .c  om
public List<String> findUnclaimedNotIndexedAfterWaitPeriod(int waitPeriodDays, int maxDaysBack, int maxResults,
        Collection<String> orcidsToExclude) {

    StringBuilder builder = new StringBuilder("SELECT orcid FROM profile p");
    builder.append(" WHERE p.claimed = false");
    builder.append(" AND p.indexing_status != :indexingStatus");
    // Has to be have been created before our min wait date
    builder.append(" AND p.date_created < now() - (CAST('1' AS INTERVAL DAY) * ");
    builder.append(waitPeriodDays);
    builder.append(")");
    // Max number of days limits how many days we go back and check
    builder.append(" AND p.date_created > now() - (CAST('1' AS INTERVAL DAY) * ");
    builder.append(maxDaysBack);
    builder.append(")");
    // Has not been indexed during the waitPeriodDays number of days after
    // creation.
    builder.append(" AND (p.last_indexed_date < p.date_created + (CAST('1' AS INTERVAL DAY) * ");
    builder.append(waitPeriodDays);
    builder.append(") OR p.last_indexed_date IS NULL)");
    if (!orcidsToExclude.isEmpty()) {
        builder.append(" AND p.orcid NOT IN :orcidsToExclude");
    }
    builder.append(" ORDER BY p.last_modified");
    Query query = entityManager.createNativeQuery(builder.toString());
    query.setParameter("indexingStatus", IndexingStatus.PENDING.name());
    if (!orcidsToExclude.isEmpty()) {
        query.setParameter("orcidsToExclude", orcidsToExclude);
    }
    query.setMaxResults(maxResults);
    return query.getResultList();
}

From source file:org.esbtools.message.admin.common.EsbMessageAdminServiceImpl.java

/**
 * Returns error message of the given queue
 * @param criteria// w  w w . j  av  a 2  s .com
 * @param fromDate
 * @param toDate
 * @param sortField
 * @param sortAsc
 * @param start
 * @param maxResults
 * @return SearchResult
 */
public SearchResult findMessagesBySearchCriteria(SearchCriteria criteria, Date fromDate, Date toDate,
        String sortField, Boolean sortAsc, Integer start, Integer maxResults) {

    SearchResult result = new SearchResult();
    long startTime = System.currentTimeMillis();

    // allow sorting only by display fields, choose time stamp if proper field is not set.
    String sortBy = (sortField == null || !getSortingFields().contains(sortField)) ? "timestamp" : sortField;

    if (maxResults > 0) {
        Query countQuery = getQueryFromCriteria(criteria, sortBy, sortAsc, fromDate, toDate, true);
        try {
            result.setTotalResults((Long) countQuery.getSingleResult());
        } catch (NoResultException e) {
            LOG.warn("No result when trying to do count of searchResults", e);
            return SearchResult.empty();
        }

        Query resultQuery = getQueryFromCriteria(criteria, sortBy, sortAsc, fromDate, toDate, false);

        resultQuery.setFirstResult(start);
        resultQuery.setMaxResults(maxResults);
        @SuppressWarnings("rawtypes")
        List searchResult = resultQuery.getResultList();

        EsbMessage[] resultMessages = new EsbMessage[searchResult.size()];
        for (int i = 0; i < resultMessages.length; i++) {
            Object[] cols = (Object[]) searchResult.get(i);
            EsbMessage msg = new EsbMessage();
            msg.setId((Long) cols[0]);
            msg.setTimestamp((Date) cols[1]);
            msg.setMessageType((String) cols[2]);
            msg.setSourceSystem((String) cols[3]);
            msg.setErrorSystem((String) cols[4]);
            msg.setOccurrenceCount((Integer) cols[5]);
            msg.setResubmittedOn((Date) cols[6]);
            msg.setAllowsResubmit(allowsResubmit(msg));
            msg.setEditableMessage(isEditableMessage(msg));
            resultMessages[i] = msg;
        }
        result.setMessages(resultMessages);
        result.setItemsPerPage(maxResults);
        result.setPage((start / maxResults) + 1);
    } else {
        result.setItemsPerPage(0);
        result.setPage(0);
    }
    long endTime = System.currentTimeMillis();
    saveAuditEvent(new AuditEvent(DEFAULT_USER, "SEARCH", ERROR_KEY_TYPE, "", "",
            criteria.toString() + ", From:" + fromDate + ", To:" + toDate + ", Sort:" + sortField + ", Asc:"
                    + sortAsc + ", start:" + start + ", maxResults:" + maxResults + " time:"
                    + (endTime - startTime)));

    return result;
}

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

@SuppressWarnings("unchecked")
@Override/*from   ww w.ja  v  a  2s .  co m*/
public List<String> findUnclaimedNeedingReminder(int remindAfterDays, int maxResults,
        Collection<String> orcidsToExclude) {
    StringBuilder builder = new StringBuilder(
            "SELECT p.orcid FROM profile p LEFT JOIN profile_event e ON e.orcid = p.orcid AND e.profile_event_type = :profileEventType");
    builder.append(" WHERE p.claimed = false");
    builder.append(
            " AND p.deprecated_date is null AND p.profile_deactivation_date is null AND p.account_expiry is null ");
    // Hasn't already been sent a reminder
    builder.append(" AND e.orcid IS NULL");
    // Has to be have been created at least remindAfterDays number of days
    // ago
    builder.append(" AND p.date_created < (now() - CAST('");
    // Doesn't seem to work correctly in postgresql when using placeholder
    // param, so wait period is inlined.
    builder.append(remindAfterDays);
    builder.append("' AS INTERVAL DAY))");
    if (!orcidsToExclude.isEmpty()) {
        builder.append(" AND p.orcid NOT IN :orcidsToExclude");
    }
    builder.append(" ORDER BY p.last_modified");
    Query query = entityManager.createNativeQuery(builder.toString());
    query.setParameter("profileEventType", ProfileEventType.CLAIM_REMINDER_SENT.name());
    if (!orcidsToExclude.isEmpty()) {
        query.setParameter("orcidsToExclude", orcidsToExclude);
    }
    query.setMaxResults(maxResults);
    return query.getResultList();
}

From source file:edu.kit.dama.mdm.core.jpa.MetaDataManagerJpa.java

@Override
public final List findResultList(String queryString, Object[] pParameters, int pFirstIdx, int pMaxResults)
        throws UnauthorizedAccessAttemptException {
    List result = new ArrayList();
    try {/*from w  w w  . j av a 2  s .co m*/
        Query q = entityManager.createQuery(queryString);
        applyProperties(q);
        if (pParameters != null && pParameters.length != 0) {
            for (int i = 0; i < pParameters.length; i++) {
                q.setParameter(i + 1, pParameters[i]);
            }
        }
        q.setFirstResult((pFirstIdx >= 0) ? pFirstIdx : 0);
        if (pMaxResults > 0) {
            q.setMaxResults(pMaxResults);
        }
        result = q.getResultList();
    } catch (RuntimeException re) {
        LOGGER.warn("Failed to obtain generic query result list", re);
    } finally {
        finalizeEntityManagerAccess("find result list with plain SQL '" + queryString + "'", null, List.class);
    }
    return result;
}

From source file:es.alvsanand.webpage.db.dao.DAOHelper.java

protected Query getQuery(EntityManager entityManager, String queryName, QueryBean queryBean) {
    StringBuffer queryString = new StringBuffer(queryName);

    Query q = null;

    if (queryBean != null) {
        if (queryBean.getOrderBeans() != null) {
            for (int i = 0; i < queryBean.getOrderBeans().size(); i++) {
                OrderBean orderBean = queryBean.getOrderBeans().get(i);

                if (StringUtils.isEmpty(orderBean.getName())) {
                    continue;
                }/*from   ww  w .j  a  v a 2 s  . co  m*/

                if (i == 0) {
                    queryString.append(ORDERBY_SPQL_TEXT);
                }

                queryString.append(orderBean.getName());
                queryString.append((orderBean.isAscendingOrder()) ? ASC_SPQL_TEXT : DES_SPQL_TEXT);
                if (i + 1 < queryBean.getOrderBeans().size()) {
                    queryString.append(", ");
                }
            }
        }

        q = entityManager.createQuery(queryString.toString());

        if (queryBean.getLimit() > 0) {
            q.setMaxResults(queryBean.getLimit());
        }
        if (queryBean.getOffset() > 0) {
            q.setFirstResult(queryBean.getOffset());
        }
    } else {
        q = entityManager.createQuery(queryName);
    }

    return q;
}

From source file:com.htm.db.spring.DataAccessRepositoryImpl.java

public List<IWorkItem> query(String whereClause, int maxResults) throws DatabaseException {

    String queryString = "SELECT * FROM Workitemtaskview wiview ";

    /* If a where clause was specified attach it to the query */
    if (!StringUtils.isEmpty(whereClause)) {
        queryString += "where " + whereClause;
    }/*from  ww  w .  ja v a 2  s . com*/
    log.debug("Query Workitemtaskview - SQL Query : " + queryString);

    /*
       * Execute a query where Workitemtaskview objects are expected to be
       * returned
       */
    Query query = em.createNativeQuery(queryString, Workitemtaskview.class);
    if (maxResults > 0) {
        query.setMaxResults(maxResults);
    }

    List<?> workItemEntities = executeMultipleResultQuery(query);

    /* List that is to be returned. It contains work item models */
    List<IWorkItem> workItems = new ArrayList<IWorkItem>();

    if (workItemEntities != null) {
        /* Create a work item from each work item view entity */
        Iterator<?> iter = workItemEntities.iterator();
        while (iter.hasNext()) {
            Workitemtaskview viewEntity = (Workitemtaskview) iter.next();
            /*
             * Get the underlying work item of the view entity
             */
            IWorkItem workItem = getWorkItem(Integer.toString(viewEntity.getWiid()));
            workItems.add(workItem);
        }
    }
    return workItems;
}

From source file:org.medici.bia.dao.user.UserDAOJpaImpl.java

/**
 * {@inheritDoc}/*from   w  w w . j  ava  2  s . c  om*/
 */
@Override
public Long countWhoIsOnlineForum() {
    DateTime dateTime = (new DateTime(System.currentTimeMillis())).minusMinutes(5);
    Query query = getEntityManager().createQuery(
            "SELECT COUNT(DISTINCT user.account) FROM User user, AccessLog accessLog WHERE user.account = accessLog.account AND user.forumJoinedDate IS NOT NULL AND (accessLog.dateAndTime > '"
                    + DateUtils.getMYSQLDateTime(dateTime) + "')");
    query.setMaxResults(1);
    return (Long) query.getSingleResult();
}

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

@SuppressWarnings("unchecked")
public List<BunMetadata> readBunsMetadataForOwnerID(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/*from   w w  w . j av  a 2s  .c o  m*/
                .createQuery("SELECT a FROM BunMetadata a WHERE a.owner.id=" + ownerid + " ORDER BY a.id");
    else
        q = entityManager.createQuery("SELECT a FROM BunMetadata a ORDER BY a.id");

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

From source file:com.mothsoft.alexis.dao.DocumentDaoImpl.java

@SuppressWarnings("unchecked")
@Override//from  ww w . j  a  va2s .  c om
public List<ImportantNamedEntity> getImportantNamedEntitiesForDocument(Long documentId, int howMany) {
    final Query query = this.em
            .createQuery("SELECT NEW com.mothsoft.alexis.domain.ImportantNamedEntity(ne.name, sum(ne.count)) "
                    + "FROM DocumentNamedEntity ne JOIN ne.document document WHERE document.id = :documentId "
                    + "GROUP BY ne.name ORDER BY sum(ne.count) DESC");
    query.setParameter("documentId", documentId);
    query.setMaxResults(howMany);
    return query.getResultList();
}

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

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

    if ((categoryid != null) && (categoryid >= 0))
        q = entityManager.createQuery(/*  www  . j  av  a2s.c  o  m*/
                "SELECT a FROM BunMetadata a WHERE a.categories.id=" + categoryid + " ORDER BY a.id");
    else
        q = entityManager.createQuery("SELECT a FROM BunMetadata a ORDER BY a.id");

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