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.medici.bia.dao.user.UserDAOJpaImpl.java

/**
 * {@inheritDoc}//from   w  w w  . ja  v  a  2  s.  c o m
 */
@Override
public User findUser(String account) {
    try {
        Query query = getEntityManager().createQuery("FROM User WHERE account=:account");
        query.setParameter("account", account);

        query.setMaxResults(1);
        return (User) query.getSingleResult();
    } catch (PersistenceException persistenceException) {

        return null;
    }
}

From source file:org.asqatasun.entity.dao.audit.ContentDAOImpl.java

@Override
public List<Content> findOrphanRelatedContentList(WebResource webResource, int start, int chunkSize) {
    if (webResource instanceof Page) {
        Query query = entityManager.createQuery("SELECT distinct rc FROM " + RelatedContentImpl.class.getName()
                + RELATED_CONTENT_KEY + JOIN_PARENT_CONTENT_SET + JOIN_WR + WEB_RESOURCE_CONDITION
                + " AND rc.httpStatusCode =:httpStatusCode");
        query.setParameter(WEB_RESOURCE_KEY, webResource);
        query.setParameter(HTTP_STATUS_CODE_KEY, DEFAULT_HTTP_STATUS_VALUE);
        query.setFirstResult(start);/*from   ww w . jav  a  2  s . c o  m*/
        query.setMaxResults(chunkSize);
        return (List<Content>) query.getResultList();
    } else if (webResource instanceof Site) {
        Query query = entityManager.createQuery("SELECT distinct rc FROM " + RelatedContentImpl.class.getName()
                + RELATED_CONTENT_KEY + JOIN_PARENT_CONTENT_SET + JOIN_WR + " WHERE w.parent.id=:idWebResource"
                + " AND rc.httpStatusCode =:httpStatusCode");
        query.setParameter(ID_WEB_RESOURCE_KEY, webResource.getId());
        query.setParameter(HTTP_STATUS_CODE_KEY, DEFAULT_HTTP_STATUS_VALUE);
        query.setFirstResult(start);
        query.setMaxResults(chunkSize);
        List<Content> contentList = (List<Content>) query.getResultList();
        flushAndCloseEntityManager();
        return contentList;
    }
    return Collections.emptyList();
}

From source file:org.opens.tanaguru.entity.dao.audit.ContentDAOImpl.java

@Override
public List<Content> findOrphanRelatedContentList(WebResource webResource, int start, int chunkSize) {
    if (webResource instanceof Page) {
        Query query = entityManager.createQuery("SELECT distinct rc FROM " + RelatedContentImpl.class.getName()
                + RELATED_CONTENT_KEY + JOIN_PARENT_CONTENT_SET + JOIN_WR + WEB_RESOURCE_CONDITION
                + " AND rc.httpStatusCode =:httpStatusCode");
        query.setParameter(WEB_RESOURCE_KEY, webResource);
        query.setParameter(HTTP_STATUS_CODE_KEY, DEFAULT_HTTP_STATUS_VALUE);
        query.setFirstResult(start);//from w  w w .  jav  a  2s  .  c o m
        query.setMaxResults(chunkSize);
        return (List<Content>) query.getResultList();
    } else if (webResource instanceof Site) {
        Query query = entityManager.createQuery("SELECT distinct rc FROM " + RelatedContentImpl.class.getName()
                + RELATED_CONTENT_KEY + JOIN_PARENT_CONTENT_SET + JOIN_WR + " WHERE w.parent.id=:idWebResource"
                + " AND rc.httpStatusCode =:httpStatusCode");
        query.setParameter(ID_WEB_RESOURCE_KEY, webResource.getId());
        query.setParameter(HTTP_STATUS_CODE_KEY, DEFAULT_HTTP_STATUS_VALUE);
        query.setFirstResult(start);
        query.setMaxResults(chunkSize);
        List<Content> contentList = (List<Content>) query.getResultList();
        flushAndCloseEntityManager();
        return contentList;
    }
    return new ArrayList<Content>();
}

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

/**
 * {@inheritDoc}//from w  w  w  .  ja va  2  s  .c  o m
 */
@Override
@SuppressWarnings("unchecked")
public final List<T> findByNamedQuery(final String name, int start, int total, final Object... params) {
    String queryString = getJpqlQuery(name);
    Query queryObject = getEntityManager().createQuery(queryString);
    if (params != null) {
        int i = 1;
        for (Object obj : params) {
            queryObject.setParameter(i, obj);
            i++;
        }
    }
    if (start > -1)
        queryObject.setFirstResult(start);
    if (total > -1)
        queryObject.setMaxResults(total);
    return queryObject.getResultList();
}

From source file:org.kuali.rice.krad.criteria.CriteriaLookupDaoJpa.java

/** gets results where the actual rows are requested. */
private <T> GenericQueryResults<T> forRowResults(final Class<T> queryClass, final QueryByCriteria criteria,
        final Criteria jpaCriteria, CountFlag flag, LookupCustomizer.Transform<T, T> transform) {
    final Query jpaQuery = new org.kuali.rice.core.framework.persistence.jpa.criteria.QueryByCriteria(
            entityManager, jpaCriteria).toQuery();
    final GenericQueryResults.Builder<T> results = GenericQueryResults.Builder.<T>create();

    //ojb's is 1 based, our query api is zero based
    final int startAtIndex = criteria.getStartAtIndex() != null ? criteria.getStartAtIndex() + 1 : 1;
    jpaQuery.setFirstResult(startAtIndex);

    if (criteria.getMaxResults() != null) {
        //not subtracting one from MaxResults in order to retrieve
        //one extra row so that the MoreResultsAvailable field can be set
        jpaQuery.setMaxResults(criteria.getMaxResults());
    }//  ww w.  j  a  va  2  s  .c  om

    @SuppressWarnings("unchecked")
    final List<T> rows = new ArrayList<T>(jpaQuery.getResultList());
    if (flag == CountFlag.INCLUDE) {
        results.setTotalRowCount(rows.size());
    }

    if (criteria.getMaxResults() != null && rows.size() > criteria.getMaxResults()) {
        results.setMoreResultsAvailable(true);
        //remove the extra row that was returned
        rows.remove(criteria.getMaxResults().intValue());
    }

    results.setResults(transformResults(rows, transform));
    return results.build();
}

From source file:org.apache.syncope.core.persistence.dao.impl.SubjectSearchDAOImpl.java

@SuppressWarnings("unchecked")
private <T extends AbstractSubject> List<T> doSearch(final Set<Long> adminRoles, final SearchCond nodeCond,
        final int page, final int itemsPerPage, final List<OrderByClause> orderBy, final SubjectType type) {

    List<Object> parameters = Collections.synchronizedList(new ArrayList<Object>());

    // 1. get the query string from the search condition
    SearchSupport svs = new SearchSupport(type);
    StringBuilder queryString = getQuery(nodeCond, parameters, type, svs);

    // 2. take into account administrative roles and ordering
    OrderBySupport orderBySupport = parseOrderBy(type, svs, orderBy);
    if (queryString.charAt(0) == '(') {
        queryString.insert(0, buildSelect(orderBySupport));
        queryString.append(buildWhere(orderBySupport, type));
    } else {//from  w  w w  . ja va2s  . c  om
        queryString.insert(0, buildSelect(orderBySupport).append('('));
        queryString.append(')').append(buildWhere(orderBySupport, type));
    }
    queryString.append(getAdminRolesFilter(adminRoles, type)).append(')').append(buildOrderBy(orderBySupport));

    // 3. prepare the search query
    Query query = entityManager.createNativeQuery(queryString.toString());

    // 4. page starts from 1, while setFirtResult() starts from 0
    query.setFirstResult(itemsPerPage * (page <= 0 ? 0 : page - 1));

    if (itemsPerPage >= 0) {
        query.setMaxResults(itemsPerPage);
    }

    // 5. populate the search query with parameter values
    fillWithParameters(query, parameters);

    LOG.debug("Native query\n{}\nwith parameters\n{}", queryString.toString(), parameters);

    // 6. Prepare the result (avoiding duplicates)
    List<T> result = new ArrayList<T>();

    for (Object subjectId : query.getResultList()) {
        long actualId;
        if (subjectId instanceof Object[]) {
            actualId = ((Number) ((Object[]) subjectId)[0]).longValue();
        } else {
            actualId = ((Number) subjectId).longValue();
        }

        T subject = type == SubjectType.USER ? (T) userDAO.find(actualId) : (T) roleDAO.find(actualId);
        if (subject == null) {
            LOG.error("Could not find {} with id {}, even though returned by the native query", type,
                    subjectId);
        } else {
            if (!result.contains(subject)) {
                result.add(subject);
            }
        }
    }

    return result;
}

From source file:org.cesecore.audit.impl.integrityprotected.IntegrityProtectedAuditorSessionBean.java

/**
 * Build a JPA Query from the supplied queryStr and criteria.
 * Optionally using startIndex and resultLimit (used if >0).
 */// ww w  .  j  a va2 s.c  om
private Query buildConditionalQuery(final EntityManager entityManager, final String queryStr,
        final QueryCriteria criteria, final int startIndex, final int resultLimit) {
    Query query = null;
    if (criteria == null) {
        query = entityManager.createQuery(queryStr);
    } else {
        QueryGenerator generator = QueryGenerator.generator(AuditRecordData.class, criteria, "a");
        final String conditions = generator.generate();
        query = entityManager.createQuery(queryStr + conditions);
        for (final String key : generator.getParameterKeys()) {
            final Object param = generator.getParameterValue(key);
            query.setParameter(key, param);
        }
    }
    if (resultLimit > 0) {
        query.setMaxResults(resultLimit);
    }
    if (startIndex > 0) {
        query.setFirstResult(startIndex - 1);
    }
    return query;
}

From source file:org.kuali.student.r2.common.criteria.impl.CriteriaLookupDaoJpaImpl.java

/** gets results where the actual rows are requested. */
private <T> GenericQueryResults<T> forRowResults(final Class<T> queryClass, final QueryByCriteria criteria,
        final Criteria jpaCriteria, CountFlag flag, LookupCustomizer.Transform<T, T> transform) {
    final Query jpaQuery = new org.kuali.student.r2.common.criteria.QueryByCriteria(entityManager, jpaCriteria)
            .toQuery();/*from  w ww. j  a  v  a  2  s .co m*/
    final GenericQueryResults.Builder<T> results = GenericQueryResults.Builder.<T>create();

    //ojb's is 1 based, our query api is zero based
    jpaQuery.setFirstResult(criteria.getStartAtIndex() != null ? criteria.getStartAtIndex() : 0);

    if (criteria.getMaxResults() != null) {
        //adding one to MaxResults in order to retrieve
        //one extra row so that the MoreResultsAvailable field can be set
        jpaQuery.setMaxResults(criteria.getMaxResults() + 1);
    }

    @SuppressWarnings("unchecked")
    final List<T> rows = new ArrayList<T>(jpaQuery.getResultList());
    if (flag == CountFlag.INCLUDE) {
        results.setTotalRowCount(rows.size());
    }

    if (criteria.getMaxResults() != null && rows.size() > criteria.getMaxResults()) {
        results.setMoreResultsAvailable(true);
        //remove the extra row that was returned
        rows.remove(criteria.getMaxResults().intValue());
    }

    results.setResults(transformResults(rows, transform));
    return results.build();
}

From source file:org.apache.syncope.core.persistence.jpa.dao.JPASubjectSearchDAO.java

@SuppressWarnings("unchecked")
private <T extends Subject<?, ?, ?>> List<T> doSearch(final Set<Long> adminRoles, final SearchCond nodeCond,
        final int page, final int itemsPerPage, final List<OrderByClause> orderBy, final SubjectType type) {

    List<Object> parameters = Collections.synchronizedList(new ArrayList<>());

    // 1. get the query string from the search condition
    SearchSupport svs = new SearchSupport(type);
    StringBuilder queryString = getQuery(nodeCond, parameters, type, svs);

    // 2. take into account administrative roles and ordering
    OrderBySupport orderBySupport = parseOrderBy(type, svs, orderBy);
    if (queryString.charAt(0) == '(') {
        queryString.insert(0, buildSelect(orderBySupport));
        queryString.append(buildWhere(orderBySupport, type));
    } else {//  w  ww. jav a 2  s. c o  m
        queryString.insert(0, buildSelect(orderBySupport).append('('));
        queryString.append(')').append(buildWhere(orderBySupport, type));
    }
    queryString.append(getAdminRolesFilter(adminRoles, type)).append(')').append(buildOrderBy(orderBySupport));

    // 3. prepare the search query
    Query query = entityManager.createNativeQuery(queryString.toString());

    // 4. page starts from 1, while setFirtResult() starts from 0
    query.setFirstResult(itemsPerPage * (page <= 0 ? 0 : page - 1));

    if (itemsPerPage >= 0) {
        query.setMaxResults(itemsPerPage);
    }

    // 5. populate the search query with parameter values
    fillWithParameters(query, parameters);

    LOG.debug("Native query\n{}\nwith parameters\n{}", queryString.toString(), parameters);

    // 6. Prepare the result (avoiding duplicates)
    List<T> result = new ArrayList<>();

    for (Object subjectId : query.getResultList()) {
        long actualId;
        if (subjectId instanceof Object[]) {
            actualId = ((Number) ((Object[]) subjectId)[0]).longValue();
        } else {
            actualId = ((Number) subjectId).longValue();
        }

        T subject = type == SubjectType.USER ? (T) userDAO.find(actualId) : (T) roleDAO.find(actualId);
        if (subject == null) {
            LOG.error("Could not find {} with id {}, even though returned by the native query", type, actualId);
        } else {
            if (!result.contains(subject)) {
                result.add(subject);
            }
        }
    }

    return result;
}

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

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

    int year = Integer.parseInt(day.substring(0, 4));
    int month = Integer.parseInt(day.substring(4, 6)) - 1;
    int date = Integer.parseInt(day.substring(6, 8));

    Calendar calBegin = new GregorianCalendar();
    calBegin.set(year, month, date, 0, 0);
    Calendar calEnd = new GregorianCalendar();
    calEnd.set(year, month, date, 23, 59);

    result.setTotal(getTotal(type, calBegin, calEnd));
    result.setOffset(offset);/*w w w . j  a  va 2  s . com*/
    result.setLimit(limit);

    EntityManager em = null;
    try {
        em = emf.createEntityManager();
        Query q = em.createNamedQuery("findUserActionsByTypeAndIntervall");
        q.setParameter("type", type);
        q.setParameter("begin", calBegin, TemporalType.TIMESTAMP);
        q.setParameter("end", calEnd, TemporalType.TIMESTAMP);
        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();
        }
    }
}