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.j2free.jpa.Controller.java

/**
 *
 * @param namedQuery/*from ww w  .  j  av  a  2 s  .c  o m*/
 * @param start
 * @param limit
 * @param parameters
 * @return
 */
public List<Object[]> namedList(String namedQuery, int start, int limit,
        KeyValuePair<String, ? extends Object>... parameters) {
    Query query = em.createNamedQuery(namedQuery);
    if (parameters != null) {
        for (KeyValuePair<String, ? extends Object> parameter : parameters) {
            query.setParameter(parameter.key, parameter.value);
        }
    }
    if (start > 0) {
        query.setFirstResult(start);
    }
    if (limit > 0) {
        query.setMaxResults(limit);
    }
    try {
        return (List<Object[]>) query.getResultList();
    } catch (NoResultException nre) {
        return null;
    }
}

From source file:org.j2free.jpa.Controller.java

/**
 *
 * @param namedQuery//  w w  w .j a  v a  2  s .c  o  m
 * @param start
 * @param limit
 * @param parameters
 * @return
 */
public List<Object[]> namedNativeList(String namedQuery, int start, int limit,
        KeyValuePair<String, ? extends Object>... parameters) {
    Query query = em.createNativeQuery(namedQuery);
    if (parameters != null) {
        for (KeyValuePair<String, ? extends Object> parameter : parameters) {
            query.setParameter(parameter.key, parameter.value);
        }
    }
    if (start > 0) {
        query.setFirstResult(start);
    }
    if (limit > 0) {
        query.setMaxResults(limit);
    }
    try {
        return (List<Object[]>) query.getResultList();
    } catch (NoResultException nre) {
        return null;
    }
}

From source file:org.apache.openejb.util.proxy.QueryProxy.java

/**
 * @param method the method/*from w  w w.ja va2 s .  c  o  m*/
 * @param args   queryName (String) -> first parameter, parameters (Map<String, ?>) or (Object[]), first and max (int) -> max follows first
 * @param type   the query type
 * @return the expected result
 */
private Object query(final Method method, final Object[] args, final QueryType type) {
    if (args.length < 1) {
        throw new IllegalArgumentException("query() needs at least the query name");
    }

    int matched = 0;
    Query query;
    if (String.class.isAssignableFrom(args[0].getClass())) {
        switch (type) {
        case NAMED:
            query = em.createNamedQuery((String) args[0]);
            break;

        case NATIVE:
            query = em.createNativeQuery((String) args[0]);
            break;

        default:
            query = em.createQuery((String) args[0]);
        }

        matched++;

        for (int i = 1; i < args.length; i++) {
            if (args[i] == null) {
                continue;
            }

            if (Map.class.isAssignableFrom(args[i].getClass())) {
                for (final Map.Entry<String, ?> entry : ((Map<String, ?>) args[i]).entrySet()) {
                    query = query.setParameter(entry.getKey(), entry.getValue());
                }
                matched++;
            } else if (args[i].getClass().isArray()) {
                final Object[] array = (Object[]) args[i];
                for (int j = 0; j < array.length; j++) {
                    query = query.setParameter(j, array[j]);
                }
                matched++;
            } else if (isInt(args[i].getClass())) {
                final int next = i + 1;
                if (args.length == next || !isInt(args[next].getClass())) {
                    throw new IllegalArgumentException("if you provide a firstResult (first int parameter)"
                            + "you should provide a maxResult too");
                }
                final int first = (Integer) args[i];
                final int max = (Integer) args[next];

                query = query.setFirstResult(first);
                query = query.setMaxResults(max);

                matched += 2;
                i++;
            } else {
                throw new IllegalArgumentException(
                        "not managed parameter " + args[i] + " of type " + args[i].getClass());
            }
        }

        if (matched != args.length) {
            throw new IllegalArgumentException(
                    "all argument was not used, please check you signature looks like:"
                            + " <ReturnType> query(String name, Map<String, ?> parameters, int firstResult, int maxResult)");
        }
    } else {
        throw new IllegalArgumentException("query() needs at least the query name of type String");
    }

    return getQueryResult(method, query);
}

From source file:org.j2free.jpa.Controller.java

/**
 *
 * @param <T>// ww w.  j ava2 s.  c o m
 * @param query
 * @param start
 * @param limit
 * @param parameters
 * @return
 */
public <T> List<T> list(Query query, int start, int limit,
        KeyValuePair<String, ? extends Object>... parameters) {
    if (parameters != null) {
        for (KeyValuePair<String, ? extends Object> parameter : parameters) {
            query.setParameter(parameter.key, parameter.value);
        }
    }
    if (start > 0) {
        query.setFirstResult(start);
    }
    if (limit > 0) {
        query.setMaxResults(limit);
    }
    try {
        return (List<T>) query.getResultList();
    } catch (NoResultException nre) {
        return null;
    }
}

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

@SuppressWarnings("serial")
@Override//from  w  ww .j a v  a  2  s.  com
public Page getUsersNotInCourse(Integer courseId, List<Authority> filteredAuthorities,
        PaginationFilter paginationFilter) throws PersistenceException {
    if (filteredAuthorities == null || filteredAuthorities.size() == 0) {
        filteredAuthorities = new ArrayList<Authority>() {
            {
                add(Authority.STUDENTS);
                add(Authority.TEACHERS);
            }
        };
    }

    Page page = new Page(paginationFilter);
    Query query = null;

    String jpql = "FROM UserRole AS userRole WHERE" + " userRole.userAuthority.authority IN (:authorities)"
            + " AND userRole.user NOT IN ("
            + "SELECT DISTINCT coursePeople.userRole.user FROM CoursePeople AS coursePeople WHERE"
            + " coursePeople.course.courseId = :courseId)";

    if (paginationFilter.getTotal() == null) {
        String countQuery = "SELECT COUNT(userRole.user) " + jpql;
        query = getEntityManager().createQuery(countQuery);
        query.setParameter("courseId", courseId);
        query.setParameter("authorities", filteredAuthorities);

        page.setTotal(new Long((Long) query.getSingleResult()));
        page.setTotalPages(PageUtils.calculeTotalPages(page.getTotal(), page.getElementsForPage()));
    } else {
        page.setTotal(paginationFilter.getTotal());
        page.setTotalPages(PageUtils.calculeTotalPages(paginationFilter.getTotal(),
                paginationFilter.getElementsForPage()));
    }

    query = getEntityManager().createQuery(
            "SELECT userRole.user " + jpql + getOrderByQuery(paginationFilter.getSortingCriterias()));
    query.setParameter("courseId", courseId);
    query.setParameter("authorities", filteredAuthorities);

    query.setFirstResult(PageUtils.calculeStart(page.getThisPage(), page.getElementsForPage()));
    query.setMaxResults(page.getElementsForPage());

    page.setList(query.getResultList());

    return page;
}

From source file:org.medici.bia.dao.userhistory.UserHistoryDAOJpaImpl.java

/**
 * {@inheritDoc}//from  w  ww .ja  v a  2s . c o  m
 */
@Override
public Page findHistory(User user, Category category, PaginationFilter paginationFilter)
        throws PersistenceException {
    Page page = new Page(paginationFilter);

    if (paginationFilter.getTotal() == null) {
        String queryString = "SELECT count(user) FROM UserHistory WHERE user=:user and category=:category and logicalDelete=false ";

        Query query = getEntityManager().createQuery(queryString);
        query.setParameter("user", user);
        query.setParameter("category", category);
        page.setTotal(new Long((Long) query.getSingleResult()));
    }

    String objectsQuery = "FROM UserHistory WHERE user=:user and category=:category and logicalDelete=false ";

    paginationFilter = generatePaginationFilterMYSQL(category, paginationFilter);

    String jpql = objectsQuery + getOrderByQuery(paginationFilter.getSortingCriterias());
    logger.debug("JPQL Query : " + jpql);

    Query query = getEntityManager().createQuery(jpql);
    query.setParameter("user", user);
    query.setParameter("category", category);
    query.setFirstResult(paginationFilter.getFirstRecord());
    query.setMaxResults(paginationFilter.getLength());
    page.setList(query.getResultList());

    return page;
}

From source file:org.medici.bia.dao.userhistory.UserHistoryDAOJpaImpl.java

/**
 * {@inheritDoc}/*from   ww  w .ja v a 2s  .  co m*/
 */
@Override
public Page findHistory(User user, Category category, PaginationFilter paginationFilter, Integer resultSize)
        throws PersistenceException {
    Page page = new Page(paginationFilter);

    if (paginationFilter.getTotal() == null) {
        String queryString = "SELECT count(user) FROM UserHistory WHERE user=:user and category=:category and logicalDelete=false ";

        Query query = getEntityManager().createQuery(queryString);
        query.setParameter("user", user);
        query.setParameter("category", category);
        // we need to force to resultSize total if result is bigger
        Long total = new Long((Long) query.getSingleResult());
        if (total > resultSize) {
            total = new Long(resultSize);
        }

        page.setTotal(total);
    }

    String queryString = "FROM UserHistory WHERE user=:user and category=:category and logicalDelete=false ORDER BY dateAndTime DESC";

    Query query = getEntityManager().createQuery(queryString);

    query.setParameter("user", user);
    query.setParameter("category", category);
    query.setFirstResult(paginationFilter.getFirstRecord());
    query.setMaxResults(page.getTotal().intValue());
    page.setList(query.getResultList());

    return page;
}

From source file:org.apache.roller.weblogger.business.jpa.JPAUserManagerImpl.java

public List getUsers(Boolean enabled, Date startDate, Date endDate, int offset, int length)
        throws WebloggerException {
    Query query = null;
    List results = null;/*from w  w  w .  j av  a2  s .c  o m*/
    boolean setRange = offset != 0 || length != -1;

    if (endDate == null)
        endDate = new Date();

    if (enabled != null) {
        if (startDate != null) {
            Timestamp start = new Timestamp(startDate.getTime());
            Timestamp end = new Timestamp(endDate.getTime());
            query = strategy.getNamedQuery("User.getByEnabled&EndDate&StartDateOrderByStartDateDesc");
            query.setParameter(1, enabled);
            query.setParameter(2, end);
            query.setParameter(3, start);
        } else {
            Timestamp end = new Timestamp(endDate.getTime());
            query = strategy.getNamedQuery("User.getByEnabled&EndDateOrderByStartDateDesc");
            query.setParameter(1, enabled);
            query.setParameter(2, end);
        }
    } else {
        if (startDate != null) {
            Timestamp start = new Timestamp(startDate.getTime());
            Timestamp end = new Timestamp(endDate.getTime());
            query = strategy.getNamedQuery("User.getByEndDate&StartDateOrderByStartDateDesc");
            query.setParameter(1, end);
            query.setParameter(2, start);
        } else {
            Timestamp end = new Timestamp(endDate.getTime());
            query = strategy.getNamedQuery("User.getByEndDateOrderByStartDateDesc");
            query.setParameter(1, end);
        }
    }
    if (offset != 0) {
        query.setFirstResult(offset);
    }
    if (length != -1) {
        query.setMaxResults(length);
    }
    return query.getResultList();
}

From source file:org.medici.bia.dao.image.ImageDAOJpaImpl.java

/**
 * {@inheritDoc}/*from   w  ww.j a  va 2  s .  c o  m*/
 */
@Override
public Page getVolumeImages(PaginationFilter paginationFilter, Integer volNum, String volLetExt,
        String[] imageTitleFilters) throws PersistenceException {
    Page page = new Page(paginationFilter);

    String jpql = "FROM Image WHERE volNum = :volNum AND volLetExt "
            + (volLetExt != null ? "= :volLetExt" : "IS NULL");
    if (imageTitleFilters != null) {
        for (int i = 0; i < imageTitleFilters.length; i++) {
            jpql += " AND imageTitle LIKE '%" + imageTitleFilters[i] + "%'";
        }
    }

    Query query = null;

    if (paginationFilter.getTotal() == null) {
        String countQuery = "SELECT COUNT(*) " + jpql;
        query = getEntityManager().createQuery(countQuery);
        query.setParameter("volNum", volNum);
        if (volLetExt != null) {
            query.setParameter("volLetExt", volLetExt);
        }
        page.setTotal(new Long((Long) query.getSingleResult()));
        page.setTotalPages(PageUtils.calculeTotalPages(page.getTotal(), page.getElementsForPage()));
    } else {
        page.setTotal(paginationFilter.getTotal());
        page.setTotalPages(PageUtils.calculeTotalPages(paginationFilter.getTotal(),
                paginationFilter.getElementsForPage()));
    }

    query = getEntityManager().createQuery(jpql + getOrderByQuery(paginationFilter.getSortingCriterias()));
    query.setParameter("volNum", volNum);
    if (volLetExt != null) {
        query.setParameter("volLetExt", volLetExt);
    }

    query.setFirstResult(PageUtils.calculeStart(page.getThisPage(), page.getElementsForPage()));
    query.setMaxResults(paginationFilter.getLength());

    page.setList(query.getResultList());

    return page;
}

From source file:io.apiman.manager.api.jpa.JpaStorage.java

/**
 * @see io.apiman.manager.api.core.IStorageQuery#getPlanVersions(java.lang.String, java.lang.String)
 *//*from ww  w .ja v  a2  s . c o  m*/
@Override
public List<PlanVersionSummaryBean> getPlanVersions(String orgId, String planId) throws StorageException {
    beginTx();
    try {
        EntityManager entityManager = getActiveEntityManager();
        String jpql = "SELECT v from PlanVersionBean v" + "  JOIN v.plan p" + "  JOIN p.organization o"
                + " WHERE o.id = :orgId" + "   AND p.id = :planId" + " ORDER BY v.createdOn DESC";
        Query query = entityManager.createQuery(jpql);
        query.setMaxResults(500);
        query.setParameter("orgId", orgId);
        query.setParameter("planId", planId);
        List<PlanVersionBean> planVersions = query.getResultList();
        List<PlanVersionSummaryBean> rval = new ArrayList<>(planVersions.size());
        for (PlanVersionBean planVersion : planVersions) {
            PlanVersionSummaryBean pvsb = new PlanVersionSummaryBean();
            pvsb.setOrganizationId(planVersion.getPlan().getOrganization().getId());
            pvsb.setOrganizationName(planVersion.getPlan().getOrganization().getName());
            pvsb.setId(planVersion.getPlan().getId());
            pvsb.setName(planVersion.getPlan().getName());
            pvsb.setDescription(planVersion.getPlan().getDescription());
            pvsb.setVersion(planVersion.getVersion());
            pvsb.setStatus(planVersion.getStatus());
            rval.add(pvsb);
        }
        return rval;
    } catch (Throwable t) {
        logger.error(t.getMessage(), t);
        throw new StorageException(t);
    } finally {
        rollbackTx();
    }
}