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.opencastproject.usertracking.impl.UserTrackingServiceImpl.java

public Report getReport(int offset, int limit) {
    Report report = new ReportImpl();
    report.setLimit(limit);/*from  w w  w . j a  va 2s. c  o m*/
    report.setOffset(offset);

    EntityManager em = null;
    try {
        em = emf.createEntityManager();
        Query q = em.createNamedQuery("countSessionsGroupByMediapackage");
        q.setFirstResult(offset);
        q.setMaxResults(limit);

        @SuppressWarnings("unchecked")
        List<Object[]> result = q.getResultList();
        ReportItem item;

        for (Object[] a : result) {
            item = new ReportItemImpl();
            item.setEpisodeId((String) a[0]);
            item.setViews((Long) a[1]);
            item.setPlayed((Long) a[2]);
            report.add(item);
        }
        return report;
    } finally {
        if (em != null && em.isOpen()) {
            em.close();
        }
    }
}

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

@Test
public void test_paginate_with_order() {
    EntityManager entityManager = newMock(EntityManager.class);
    Query query = newMock(Query.class);
    Query query2 = newMock(Query.class);
    expect(entityManager.createQuery(//w  w  w. ja va 2 s .c o m
            "select root.id from corner.orm.gae.impl.TestAEntity as root  where name=:1 order by id desc"))
                    .andReturn(query);
    expect(entityManager
            .createQuery("select count(root)  from corner.orm.gae.impl.TestAEntity as root  where name=:1"))
                    .andReturn(query2);
    expect(query.setParameter("1", "acai")).andReturn(query);
    expect(query2.setParameter("1", "acai")).andReturn(query2);
    expect(query.setFirstResult(0)).andReturn(query);
    expect(query.setMaxResults(10)).andReturn(query);
    List listValue = Collections.EMPTY_LIST;
    expect(query.getResultList()).andReturn(listValue);
    expect(query2.getSingleResult()).andReturn(new Integer(1234));

    JpaTemplate jpaTemplate = GaeModule.buildJpaTemplate(entityManager);
    replay();
    PaginatedJapEntityService pjes = new PaginatedJapEntityService(jpaTemplate, typeCoercer);
    PaginationOptions options = new PaginationOptions();
    PaginationList pl = pjes.paginate(TestAEntity.class, new String[] { "name=:1", "acai" }, "id desc",
            options);
    assertFalse(((Iterator) pl.collectionObject()).hasNext());
    PaginationOptions optionsR = pl.options();
    assertEquals(1234, optionsR.getTotalRecord());
    verify();
}

From source file:com.impetus.kundera.rest.common.EntityUtils.java

/**
 * @param queryString//  ww  w .j  av  a2 s .c  o  m
 * @param q
 */
public static void setQueryParameters(String queryString, HashMap<String, String> paramsMap, Query q) {
    KunderaQuery kq = ((QueryImpl) q).getKunderaQuery();
    Set<Parameter<?>> parameters = kq.getParameters();
    for (String paramName : paramsMap.keySet()) {
        String value = paramsMap.get(paramName);

        if (StringUtils.isNumeric(paramName)) {
            for (Parameter param : parameters) {
                if (param.getPosition() == Integer.parseInt(paramName)) {
                    Class<?> paramClass = param.getParameterType();
                    PropertyAccessor accessor = PropertyAccessorFactory.getPropertyAccessor(paramClass);
                    Object paramValue = accessor.fromString(paramClass, value);
                    q.setParameter(Integer.parseInt(paramName), paramValue);
                    break;
                }
            }
        } else {
            for (Parameter param : parameters) {
                if (param.getName().equals(paramName)) {
                    Class<?> paramClass = param.getParameterType();
                    PropertyAccessor accessor = PropertyAccessorFactory.getPropertyAccessor(paramClass);
                    Object paramValue = accessor.fromString(paramClass, value);
                    if (paramName.equalsIgnoreCase("firstResult")) {
                        q.setFirstResult(Integer.parseInt((String) paramValue));
                    } else if (paramName.equalsIgnoreCase("maxResult")) {
                        q.setMaxResults(Integer.parseInt((String) paramValue));
                    } else {
                        q.setParameter(paramName, paramValue);
                    }
                    break;
                }
            }

        }
    }
}

From source file:com.sun.socialsite.business.impl.JPAGroupManagerImpl.java

/**
 * Note: using SuppressWarnings annotation because the JPA API is not genericized.
 *//*from  w ww. j  a v  a2  s.  c om*/
@SuppressWarnings(value = "unchecked")
public List<Group> getMostRecentlyUpdatedGroups(int offset, int length) throws SocialSiteException {
    Query query = strategy.getNamedQuery("Group.getMostRecentlyUpdated");
    if (offset != 0) {
        query.setFirstResult(offset);
    }
    if (length != -1) {
        query.setMaxResults(length);
    }
    return (List<Group>) query.getResultList();
}

From source file:com.sun.socialsite.business.impl.JPAGroupManagerImpl.java

/**
 * Note: using SuppressWarnings annotation because the JPA API is not genericized.
 *//*from ww  w .  java2 s.  c o m*/
@SuppressWarnings(value = "unchecked")
public List<Group> getPopularGroups(int offset, int length) throws SocialSiteException {
    Query query = strategy.getNamedQuery("GroupRelationship.getPopularGroups");
    if (offset != 0) {
        query.setFirstResult(offset);
    }
    if (length != -1) {
        query.setMaxResults(length);
    }
    return (List<Group>) query.getResultList();
}

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

/**
 * {@inheritDoc}/*from   w w  w.  j ava  2  s . c o  m*/
 */
@Override
@SuppressWarnings("unchecked")
public final List<T> findAll(int start, int total) {
    Query query = getEntityManager().createQuery("select obj from " + getEntityBeanType().getName() + " obj ");
    if (start > -1)
        query.setFirstResult(start);
    if (total > -1)
        query.setMaxResults(total);
    return query.getResultList();
}

From source file:com.maomao.framework.dao.jpa.RedisDaoSupportImpl.java

/**
 * Query count from db./*from w  ww  .  ja v  a  2  s .  c o m*/
 */
public List<?> findCount(final String jpql, final Object[] params, final int firstResult,
        final int maxResults) {
    StringBuffer qlwithParams = new StringBuffer(jpql.length());
    char c;
    for (int i = 0; i < jpql.length(); i++) {
        c = jpql.charAt(i);
        if (jpql.charAt(i) == '?') {
            qlwithParams.append("?" + i);
        } else
            qlwithParams.append(c);
    }

    Query query = entityManager.createQuery(jpql);

    if (params != null) {
        int idx = 1;
        for (Object o : params) {
            query.setParameter(idx++, o);
        }
    }

    if (firstResult > 0)
        query.setFirstResult(firstResult);
    if (maxResults > 0)
        query.setMaxResults(maxResults);
    return query.getResultList();
}

From source file:org.easy.criteria.QueryProperties.java

public void applyProperties(Query query) {
    if (flashMode != null) {
        log.debug("flashMode = " + flashMode);
        query.setFlushMode(flashMode);/*from  w w  w.  j a v  a2 s.c om*/
    }

    if (lockMode != null) {
        log.debug("lockMode = " + lockMode);
        query.setLockMode(lockMode);
    }

    if (hintKey != null) {
        log.debug("hintKey = " + hintKey);
        log.debug("hintValue = " + hintValue);
        query.setHint(hintKey, hintValue);
    }

    if (startIndex >= 0 && maxResult > 0) {
        log.debug("startIndex = " + startIndex * maxResult);
        query.setFirstResult(startIndex * maxResult);
    }

    if (maxResult > 0) {
        log.debug("maxResult = " + maxResult);
        query.setMaxResults(maxResult);
    }
}

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

@Override
public List<TopicActivityDataSet> findMostActiveTopicDataSets(Long userId, Timestamp startDate,
        Timestamp endDate, int limit) {
    final Query query = this.em
            .createQuery("SELECT tads, SUM(pt.y) FROM TopicActivityDataSet tads LEFT JOIN tads.points pt "
                    + " WHERE tads.userId = :userId AND pt.x >= :startDate "
                    + "       AND pt.x <= :endDate AND tads.aggregate = false                 "
                    + "       AND pt.y > 0.0                                                  "
                    + " GROUP BY tads.id HAVING SUM(pt.y) > 0 ORDER BY SUM(pt.y) DESC ");
    query.setParameter("userId", userId);
    query.setParameter("startDate", startDate);
    query.setParameter("endDate", endDate);
    query.setMaxResults(limit);

    final List<?> objects = query.getResultList();
    final List<TopicActivityDataSet> dataSets = new ArrayList<TopicActivityDataSet>(limit);

    for (final Object ith : objects) {
        final Object[] array = (Object[]) ith;
        dataSets.add((TopicActivityDataSet) array[0]);
    }//from  ww  w. j a v a 2s .  c  om

    return dataSets;
}

From source file:org.opencastproject.usertracking.impl.UserTrackingServiceImpl.java

@SuppressWarnings("unchecked")
public UserActionList getUserActionsByType(String type, int offset, int limit) {
    UserActionList result = new UserActionListImpl();

    result.setTotal(getTotal(type));//from ww  w  .j  a  va2 s.  co m
    result.setOffset(offset);
    result.setLimit(limit);

    EntityManager em = null;
    try {
        em = emf.createEntityManager();
        Query q = em.createNamedQuery("findUserActionsByType");
        q.setParameter("type", type);
        q.setFirstResult(offset);
        q.setMaxResults(limit);
        Collection<UserAction> userActions = q.getResultList();

        for (UserAction a : userActions) {
            result.add(a);
        }
        return result;
    } finally {
        if (em != null && em.isOpen()) {
            em.close();
        }
    }
}