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:ltistarter.lti.LTIRequest.java

/**
 * Loads up the data which is referenced in this LTI request (assuming it can be found in the DB)
 *
 * @param repos the repos accessor used to load the data (must be set)
 * @return true if any data was loaded OR false if none could be loaded (because no matching data was found or the input keys are not set)
 *///from ww w. java  2 s  .  c om
@Transactional
public boolean loadLTIDataFromDB(AllRepositories repos) {
    assert repos != null;
    loaded = false;
    if (ltiConsumerKey == null) {
        // don't even attempt this without a key, it's pointless
        log.info("LTIload: No key to load results for");
        return false;
    }
    boolean includesService = (ltiServiceId != null);
    boolean includesSourcedid = (ltiSourcedid != null);

    StringBuilder sb = new StringBuilder();
    sb.append("SELECT k, c, l, m, u"); //k.keyId, k.keyKey, k.secret, c.contextId, c.title AS contextTitle, l.linkId, l.title AS linkTitle, u.userId, u.displayName AS userDisplayName, u.email AS userEmail, u.subscribe, u.userSha256, m.membershipId, m.role, m.roleOverride"); // 15

    if (includesService) {
        sb.append(", s"); //, s.serviceId, s.serviceKey AS service"); // 2
    }
    if (includesSourcedid) {
        sb.append(", r"); //, r.resultId, r.sourcedid, r.grade"); // 3
    }
    /*
    if (includeProfile) {
    sb.append(", p"); //", p.profileId, p.displayName AS profileDisplayName, p.email AS profileEmail, p.subscribe AS profileSubscribe"); // 4
    }*/

    sb.append(" FROM LtiKeyEntity k " + "LEFT JOIN k.contexts c ON c.contextSha256 = :context " + // LtiContextEntity
            "LEFT JOIN c.links l ON l.linkSha256 = :link " + // LtiLinkEntity
            "LEFT JOIN c.memberships m " + // LtiMembershipEntity
            "LEFT JOIN m.user u ON u.userSha256 = :user " // LtiUserEntity
    );

    if (includesService) {
        sb.append(" LEFT JOIN k.services s ON s.serviceSha256 = :service"); // LtiServiceEntity
    }
    if (includesSourcedid) {
        sb.append(" LEFT JOIN u.results r ON r.sourcedidSha256 = :sourcedid"); // LtiResultEntity
    }
    /*
    if (includeProfile) {
    sb.append(" LEFT JOIN u.profile p"); // ProfileEntity
    }*/
    sb.append(" WHERE k.keySha256 = :key AND (m IS NULL OR (m.context = c AND m.user = u))");
    /*
    if (includeProfile) {
    sb.append(" AND (u IS NULL OR u.profile = p)");
    }*/

    String sql = sb.toString();
    Query q = repos.entityManager.createQuery(sql);
    q.setMaxResults(1);
    q.setParameter("key", BaseEntity.makeSHA256(ltiConsumerKey));
    q.setParameter("context", BaseEntity.makeSHA256(ltiContextId));
    q.setParameter("link", BaseEntity.makeSHA256(ltiLinkId));
    q.setParameter("user", BaseEntity.makeSHA256(ltiUserId));
    if (includesService) {
        q.setParameter("service", BaseEntity.makeSHA256(ltiServiceId));
    }
    if (includesSourcedid) {
        q.setParameter("sourcedid", BaseEntity.makeSHA256(ltiSourcedid));
    }
    @SuppressWarnings("unchecked")
    List<Object[]> rows = q.getResultList();
    if (rows == null || rows.isEmpty()) {
        log.info("LTIload: No results found for key=" + ltiConsumerKey);
    } else {
        // k, c, l, m, u, s, r
        Object[] row = rows.get(0);
        if (row.length > 0)
            key = (LtiKeyEntity) row[0];
        if (row.length > 1)
            context = (LtiContextEntity) row[1];
        if (row.length > 2)
            link = (LtiLinkEntity) row[2];
        if (row.length > 3)
            membership = (LtiMembershipEntity) row[3];
        if (row.length > 4)
            user = (LtiUserEntity) row[4];
        if (includesService && includesSourcedid) {
            if (row.length > 5)
                service = (LtiServiceEntity) row[5];
            if (row.length > 6)
                result = (LtiResultEntity) row[6];
        } else if (includesService) {
            if (row.length > 5)
                service = (LtiServiceEntity) row[5];
        } else if (includesSourcedid) {
            if (row.length > 5)
                result = (LtiResultEntity) row[5];
        }

        // handle SPECIAL post lookup processing
        // If there is an appropriate role override variable, we use that role
        if (membership != null && membership.getRoleOverride() != null) {
            int roleOverrideNum = membership.getRoleOverride();
            if (roleOverrideNum > userRoleNumber) {
                userRoleNumber = roleOverrideNum;
            }
        }

        // check if the loading resulted in a complete set of LTI data
        checkCompleteLTIRequest(true);
        loaded = true;
        log.info("LTIload: loaded data for key=" + ltiConsumerKey + " and context=" + ltiContextId
                + ", complete=" + complete);
    }
    return loaded;
}

From source file:org.eurekastreams.server.persistence.DomainEntityMapper.java

/**
 * Get a PagedSet of type V, built from the input query string.
 * /*from  w w w  .  j  av  a  2s . com*/
 * @param <V>
 *            the type of objects to return
 * @param from
 *            the starting index
 * @param to
 *            the ending index
 * @param queryString
 *            the query string
 * @param parameters
 *            the parameters to inject into the query string
 * @return a paged set of objects of type V as built from the input query string
 */
@SuppressWarnings("unchecked")
public <V> PagedSet<V> getTypedPagedResults(final int from, final int to, final String queryString,
        final HashMap<String, Object> parameters) {
    PagedSet<V> results = new PagedSet<V>();

    log.debug("from: " + from + ", to: " + to);

    if (!results.isRangeValid(from, to)) {
        throw new IllegalArgumentException("from/to are invalid");
    }

    // TODO construct count query to avoid returning results of an entire
    // query just to get the count
    // like getPagedResults() does.
    // these didn't work:
    // "select count(q) from (select c.ideas from Campaign c where c.id=" +
    // containerId + ") q";
    // "select count(c.ideas) from Campaign c where c.id=id"

    Query count = entityManager.createQuery(queryString);
    for (String key : parameters.keySet()) {
        count.setParameter(key, parameters.get(key));
    }

    int total = count.getResultList().size();

    // if no results, return empty set
    if (total == 0) {
        return results;
    }

    // return valid range even if you requested out of range
    int validTo = to;
    if (to >= total) {
        log.debug("to>=total - to: " + to + ", total: " + total);
        validTo = total - 1;
    }
    log.debug("Query: " + queryString + ", total: " + total + ", validTo: " + validTo);

    // query to get the actual results
    Query select = entityManager.createQuery(queryString);
    for (String key : parameters.keySet()) {
        select.setParameter(key, parameters.get(key));
    }

    select.setFirstResult(from);
    int maxResults = validTo - from + 1;
    if (maxResults <= 0) {
        log.debug("Maxresults would have been negative or zero - "
                + "most likely an error on the client - returning no records");
        return results;
    }
    select.setMaxResults(maxResults);

    ArrayList<V> resultList = (ArrayList<V>) select.getResultList();

    results.setFromIndex(from);
    results.setToIndex(validTo);
    results.setTotal(total);
    results.setPagedSet(resultList);

    return results;
}

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

@SuppressWarnings("unchecked")
public List<BakerUser> readUsers(int firstResult, int maxResults) {
    EntityManager entityManager = entityManagerFactory.createEntityManager();

    Query q = entityManager.createQuery("SELECT m FROM BakerUser m");
    q.setFirstResult(firstResult);//from w  ww.  j a  v a2  s. co  m
    q.setMaxResults(maxResults);
    return q.getResultList();
}

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

@SuppressWarnings("unchecked")
public List<InstalledBun> readInstalledBuns(int firstResult, int maxResults) {
    EntityManager entityManager = entityManagerFactory.createEntityManager();

    Query q = entityManager.createQuery("SELECT m FROM InstalledBun m");
    q.setFirstResult(firstResult);//  w  w w. ja  v a2 s  .  c om
    q.setMaxResults(maxResults);
    return q.getResultList();
}

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

/**
 * {@inheritDoc}/*from w  w  w. j av  a 2s . c  o m*/
 */
@Override
public Long countMembersForum() {
    Query query = getEntityManager().createQuery("SELECT COUNT(account) FROM User");
    query.setMaxResults(1);
    return (Long) query.getSingleResult();
}

From source file:com.music.dao.Dao.java

@SuppressWarnings("unchecked")
protected <T> List<T> findByQuery(QueryDetails details) {
    Query q = null;
    if (details.getQueryName() != null) {
        q = entityManager.createNamedQuery(details.getQueryName());
    } else if (details.getQuery() != null) {
        q = entityManager.createQuery(details.getQuery());
    } else {//from   w  ww . j  a v  a2s . com
        throw new IllegalArgumentException("Either query or query name must be set");
    }

    for (int i = 0; i < details.getParamNames().length; i++) {
        q.setParameter(details.getParamNames()[i], details.getParamValues()[i]);
    }
    if (details.getStart() > -1) {
        q.setFirstResult(details.getStart());
    }
    if (details.getCount() > -1) {
        q.setMaxResults(details.getCount());
    }
    if (details.isCacheable()) {
        setCacheable(q);
    }
    return q.getResultList();
}

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

public List<SubscribedResource> readSubscribedResources(int firstResult, int maxResults) {
    EntityManager entityManager = entityManagerFactory.createEntityManager();

    Query q = entityManager.createQuery("SELECT m FROM SubscribedResource m");
    q.setFirstResult(firstResult);/*from   w w w . j  a  v a  2 s .  c om*/
    q.setMaxResults(maxResults);
    return q.getResultList();
}

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

public List<BakerProperty> readProperties(int firstResult, int maxResults) {
    EntityManager entityManager = entityManagerFactory.createEntityManager();

    Query q = entityManager.createQuery("SELECT m FROM BakerProperty m  ORDER BY m.id");
    q.setFirstResult(firstResult);// w  w  w . ja v a  2 s.  co m
    q.setMaxResults(maxResults);
    return q.getResultList();

}

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

@SuppressWarnings("unchecked")
@Override/*  w  ww. j a v a2 s.  c  o m*/
public List<String> findEmailsUnverfiedDays(int daysUnverified, int maxResults, EmailEventType ev) {
    // @formatter:off
    String queryStr = "SELECT e.email FROM email e " + "LEFT JOIN email_event ev ON e.email = ev.email "
            + "AND (ev.email_event_type = :evt or ev.email_event_type='VERIFY_EMAIL_7_DAYS_SENT_SKIPPED') "
            + "JOIN profile p on p.orcid = e.orcid and p.claimed = true "
            + "AND p.deprecated_date is null AND p.profile_deactivation_date is null AND p.account_expiry is null "
            + "where ev.email IS NULL " + "and e.is_verified = false " + "and e.date_created < (now() - CAST('"
            + daysUnverified + "' AS INTERVAL DAY)) " + "and (e.source_id = e.orcid OR e.source_id is null)"
            + " ORDER BY e.last_modified";
    // @formatter:on
    Query query = entityManager.createNativeQuery(queryStr);
    query.setParameter("evt", ev.name());
    query.setMaxResults(maxResults);
    return query.getResultList();
}

From source file:net.firejack.platform.core.store.BaseStore.java

private Query getNamedQuery(Session session, String queryName, Integer offset, Integer limit) {
    Query query = session.getNamedQuery(queryName);
    if (offset != null && offset > -1) {
        query.setFirstResult(offset);/* w  ww . j a  va2 s . co  m*/
    }
    if (limit != null && limit > -1) {
        query.setMaxResults(limit);
    }
    return query;
}