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:com.doculibre.constellio.services.RecordServicesImpl.java

@SuppressWarnings("unchecked")
private List<Record> list(RecordCollection collection, int maxResults, Boolean updateIndex,
        Boolean excludedOrDeleted) {
    String ql = "FROM Record r WHERE r.connectorInstance.recordCollection = :recordCollection";
    if (Boolean.TRUE.equals(updateIndex)) {
        ql += " AND updateIndex = true AND ((deleted = false OR deleted = null) AND (excluded = false OR excluded = null))";
    }//ww w. ja  va 2s  .  co m
    if (Boolean.TRUE.equals(excludedOrDeleted)) {
        ql += " AND (deleted = true OR (excluded = true AND excludedEffective = false))";
    }
    ql += " ORDER BY r.id ASC";
    Query query = this.getEntityManager().createQuery(ql);
    query.setParameter("recordCollection", collection);
    if (maxResults >= 0) {
        query.setMaxResults(maxResults);
    }
    return (List<Record>) query.getResultList();
}

From source file:org.eurekastreams.server.persistence.mappers.db.StreamPopularHashTagsDbMapper.java

/**
 * Get the popular hashtags for the input Group/Person stream.
 * // www .j a  v  a2  s . c o m
 * @param inRequest
 *            type of stream and unique key of the entity stream to fetch hashtags for
 * @return the list of popular hashtags
 */
public StreamPopularHashTagsReportDTO execute(final StreamPopularHashTagsRequest inRequest) {
    Calendar calendar = Calendar.getInstance();
    calendar.add(Calendar.HOUR, 0 - popularHashTagWindowInHours);
    Date minActivityTime = calendar.getTime();

    if (log.isDebugEnabled()) {
        log.debug("Looking for " + maxNumberOfPopularHashTags + " popular hashtags for "
                + inRequest.getStreamEntityScopeType() + " stream with id "
                + inRequest.getStreamEntityUniqueKey() + " and activity date >= " + minActivityTime.toString());
    }

    Query query = getEntityManager()
            .createQuery("SELECT hashTag.content FROM StreamHashTag WHERE streamScopeType = :streamScopeType "
                    + "AND activityDate >= :activityDate AND streamEntityUniqueKey = :streamEntityUniqueKey "
                    + "GROUP BY hashTag.content ORDER BY COUNT(hashTag.content) DESC, hashTag.content ASC")
            .setParameter("streamScopeType", inRequest.getStreamEntityScopeType())
            .setParameter("activityDate", minActivityTime)
            .setParameter("streamEntityUniqueKey", inRequest.getStreamEntityUniqueKey());
    query.setMaxResults(maxNumberOfPopularHashTags);

    List<String> hashTags = query.getResultList();

    if (log.isDebugEnabled()) {
        log.debug("Found popular hashtags: " + hashTags + " for " + inRequest.getStreamEntityScopeType()
                + " stream with id " + inRequest.getStreamEntityUniqueKey() + " and activity date >= "
                + minActivityTime.toString());
    }

    Calendar now = Calendar.getInstance();
    return new StreamPopularHashTagsReportDTO(hashTags, now.getTime());
}

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);
    }//w  w w  .  ja v  a2s  . c om

    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:com.impetus.ankush.common.dao.impl.GenericDaoJpa.java

@SuppressWarnings(UNCHECKED)
public List<T> getAllByPropertyValue(Map<String, Object> propertyValueMap, int start, int maxResults,
        String... orderBy) {/*from  w  w  w .j  av  a 2 s.com*/
    Query query = createSelectQuery(propertyValueMap, orderBy);
    query.setFirstResult(start);
    query.setMaxResults(maxResults);
    return query.getResultList();
}

From source file:org.openhab.persistence.jpa.internal.JpaPersistenceService.java

@Override
public Iterable<HistoricItem> query(FilterCriteria filter) {
    logger.debug("Querying for historic item: {}", filter.getItemName());

    if (!JpaConfiguration.isInitialized) {
        logger.warn("Trying to create EntityManagerFactory but we don't have configuration yet!");
        return Collections.emptyList();
    }//from  w w  w. j  a va2  s.com

    String itemName = filter.getItemName();
    Item item = getItemFromRegistry(itemName);

    String sortOrder;
    if (filter.getOrdering() == Ordering.ASCENDING)
        sortOrder = "ASC";
    else
        sortOrder = "DESC";

    boolean hasBeginDate = false;
    boolean hasEndDate = false;
    String queryString = "SELECT n FROM " + JpaPersistentItem.class.getSimpleName()
            + " n WHERE n.realName = :itemName";
    if (filter.getBeginDate() != null) {
        queryString += " AND n.timestamp >= :beginDate";
        hasBeginDate = true;
    }
    if (filter.getEndDate() != null) {
        queryString += " AND n.timestamp <= :endDate";
        hasEndDate = true;
    }
    queryString += " ORDER BY n.timestamp " + sortOrder;

    logger.debug("The query: " + queryString);

    EntityManager em = getEntityManagerFactory().createEntityManager();
    try {
        // In RESOURCE_LOCAL calls to EntityManager require a begin/commit
        em.getTransaction().begin();

        logger.debug("Creating query...");
        Query query = em.createQuery(queryString);
        query.setParameter("itemName", item.getName());
        if (hasBeginDate)
            query.setParameter("beginDate", filter.getBeginDate());
        if (hasEndDate)
            query.setParameter("endDate", filter.getEndDate());

        query.setFirstResult(filter.getPageNumber() * filter.getPageSize());
        query.setMaxResults(filter.getPageSize());
        logger.debug("Creating query...done");

        logger.debug("Retrieving result list...");
        @SuppressWarnings("unchecked")
        List<JpaPersistentItem> result = (List<JpaPersistentItem>) query.getResultList();
        logger.debug("Retrieving result list...done");

        List<HistoricItem> historicList = JpaHistoricItem.fromResultList(result, item);
        if (historicList != null) {
            logger.debug(String.format("Convert to HistoricItem: %d", historicList.size()));
        }

        em.getTransaction().commit();

        return historicList;

    } catch (Exception e) {
        logger.error("Error on querying database!");
        logger.error(e.getMessage(), e);
        em.getTransaction().rollback();

    } finally {
        em.close();
    }

    return Collections.emptyList();
}

From source file:eu.forgestore.ws.impl.FStoreJpaController.java

public List<Widget> readWidgetMetadataByOwnerId(int userid, int firstResult, int maxResults) {
    EntityManager entityManager = entityManagerFactory.createEntityManager();
    Query q;

    q = entityManager.createQuery("SELECT a FROM Widget a WHERE a.owner.id=" + userid + " ORDER BY a.id");

    q.setFirstResult(firstResult);/*from  www.  ja  va  2s .c  o m*/
    q.setMaxResults(maxResults);
    return q.getResultList();
}

From source file:eu.forgestore.ws.impl.FStoreJpaController.java

public List<Course> readCoursesMetadataByOwnerId(int userid, int firstResult, int maxResults) {
    EntityManager entityManager = entityManagerFactory.createEntityManager();
    Query q;

    q = entityManager.createQuery("SELECT a FROM Course a WHERE a.owner.id=" + userid + " ORDER BY a.id");

    q.setFirstResult(firstResult);//from   w ww. j  a  va2 s  .co  m
    q.setMaxResults(maxResults);
    return q.getResultList();
}

From source file:eu.forgestore.ws.impl.FStoreJpaController.java

public List<FIREAdapter> readFIREAdaptersMetadataByOwnerId(int userid, int firstResult, int maxResults) {
    EntityManager entityManager = entityManagerFactory.createEntityManager();
    Query q;

    q = entityManager.createQuery("SELECT a FROM FIREAdapter a WHERE a.owner.id=" + userid + " ORDER BY a.id");

    q.setFirstResult(firstResult);//w w w .  jav a  2s.co  m
    q.setMaxResults(maxResults);
    return q.getResultList();
}

From source file:com.impetus.ankush.common.dao.impl.GenericDaoJpa.java

public List<T> getAll(int start, int maxResults, String... orderBy) {
    Query query = this.entityManager.createQuery(getAllQueryString() + createOrderByClause(orderBy));

    query.setFirstResult(start);/*from  ww w .java 2 s . c o  m*/
    query.setMaxResults(maxResults);

    return query.getResultList();
}

From source file:com.openmeap.model.ModelServiceImpl.java

@Override
public ApplicationArchive findApplicationArchiveByHashAndAlgorithm(Application app, String hash,
        String hashAlgorithm) {//from   w  ww . ja v  a  2  s.c om
    Query q = entityManager.createQuery(
            "select distinct ar " + "from ApplicationArchive ar " + "join fetch ar.application app "
                    + "where ar.hash=:hash " + "and ar.hashAlgorithm=:hashAlgorithm " + "and app.id=:appId");
    q.setParameter("hash", hash);
    q.setParameter("hashAlgorithm", hashAlgorithm);
    q.setParameter("appId", app.getId());
    q.setMaxResults(1);
    try {
        ApplicationArchive o = (ApplicationArchive) q.getSingleResult();
        return (ApplicationArchive) o;
    } catch (NoResultException nre) {
        return null;
    }
}