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  ww. j  a v  a2  s. c o m*/
 */
@Override
public User getNewestMember() {
    try {
        Query query = getEntityManager().createQuery("FROM User ORDER BY forumJoinedDate DESC");

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

        return null;
    }
}

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

/**
 * {@inheritDoc}//from ww w.  j  av  a  2 s  . c o m
 */
public List<MediaFile> fetchRecentPublicMediaFiles(int length) throws WebloggerException {

    List<Object> params = new ArrayList<Object>();
    int size = 0;
    StringBuilder queryString = new StringBuilder();

    queryString.append("SELECT m FROM MediaFile m WHERE m.sharedForGallery = true");
    queryString.append(" order by m.dateUploaded");
    Query query = strategy.getDynamicQuery(queryString.toString());
    query.setFirstResult(0);
    query.setMaxResults(length);
    return query.getResultList();
}

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

public UserActionList getUserActionsByTypeAndMediapackageId(String type, String mediapackageId, int offset,
        int limit) {
    UserActionList result = new UserActionListImpl();

    result.setTotal(getTotal(type, mediapackageId));
    result.setOffset(offset);//from w w  w .ja v a 2 s  .co m
    result.setLimit(limit);

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

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

From source file:org.medici.bia.dao.titleoccslist.TitleOccsListDAOJpaImpl.java

/**
 * {@inheritDoc}//from w ww  . j a  va2 s  .c  om
 */
@SuppressWarnings("unchecked")
@Override
public Page searchTitlesOrOccupations(SimpleSearchTitleOrOccupation simpleSearchTitleOrOccupation,
        PaginationFilter paginationFilter) throws PersistenceException {
    // We prepare object of return method.
    Page page = new Page(paginationFilter);

    // select a.TitleOccID, a.TitleOcc, count(b.personId) from tblTitleOccsList a left outer join tblPoLink b on b.TitleOccID = a.TitleOccID group by a.titleOccID
    StringBuilder stringBuilder = new StringBuilder(
            "select a.titleOccID, a.titleOcc, count(b.personId) from tblTitleOccsList a");
    stringBuilder.append(" left join tblPoLink b on b.titleOccID = a.TitleOccID ");
    if (simpleSearchTitleOrOccupation.getTextSearch() != null) {
        stringBuilder.append(" where a.titleOcc LIKE '%");
        stringBuilder.append(simpleSearchTitleOrOccupation.getTextSearch());
        stringBuilder.append("%' ");
    } else if (simpleSearchTitleOrOccupation.getRoleCatId() != null) {
        stringBuilder.append(" where a.roleCatMinorId=");
        stringBuilder.append(simpleSearchTitleOrOccupation.getRoleCatId());
    }
    stringBuilder.append(" group by a.titleOccID ");

    // We set size of result.
    if (paginationFilter.getTotal() == null) {
        //select  count(*) from ( select count(*) from tblTitleOccsList a left outer join tblPoLink b on b.TitleOccID = a.TitleOccID group by a.titleOccID ) count
        StringBuilder queryCountBuilder = new StringBuilder("");
        queryCountBuilder.append("select count(*) from tblTitleOccsList a ");
        if (simpleSearchTitleOrOccupation.getTextSearch() != null) {
            queryCountBuilder.append(" where a.titleOcc LIKE '%");
            queryCountBuilder.append(simpleSearchTitleOrOccupation.getTextSearch());
            queryCountBuilder.append("%' ");
        } else if (simpleSearchTitleOrOccupation.getRoleCatId() != null) {
            queryCountBuilder.append(" where a.roleCatMinorID=");
            queryCountBuilder.append(simpleSearchTitleOrOccupation.getRoleCatId());
        }

        // In this case we use Native Query!!!
        Query query = getEntityManager().createNativeQuery(queryCountBuilder.toString());

        // Count(*) in native query is mapped as BigInteger, so we need to convert to Long...
        BigInteger result = (BigInteger) query.getSingleResult();
        page.setTotal(NumberUtils.createLong(result.toString()));
    }

    // We invoke native query beacuse we use left outer join with on condition 
    Query query = getEntityManager().createNativeQuery(stringBuilder.toString());
    query.setFirstResult(paginationFilter.getFirstRecord());
    query.setMaxResults(paginationFilter.getLength());

    List<Object> list = (List<Object>) query.getResultList();

    List<Object> result = new ArrayList<Object>(list.size());

    for (int i = 0; i < list.size(); i++) {
        Object[] singleRow = (Object[]) list.get(i);
        List<Object> row = new ArrayList<Object>(0);

        row.add(new TitleOccsList((Integer) singleRow[0], (String) singleRow[1]));
        row.add(NumberUtils.createLong(((BigInteger) singleRow[2]).toString()));
        result.add(row);
    }

    // We set search result on return method
    page.setList(result);

    return page;
}

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

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

    Query q = entityManager.createQuery("SELECT m FROM DeploymentDescriptor m  ORDER BY m.id");
    q.setFirstResult(firstResult);//from w  w w.ja  v a2  s.  c  o  m
    q.setMaxResults(maxResults);
    return q.getResultList();
}

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

public Document findAndLockOneDocument(final DocumentState state) {
    final Query query = this.em.createQuery("from Document where intState = :state order by id asc");
    query.setParameter("state", state.getValue());
    query.setMaxResults(1);

    @SuppressWarnings("unchecked")
    final List<Document> results = query.getResultList();

    if (results.isEmpty()) {
        return null;
    }/*from  w  ww  . j  ava 2s .c  o m*/

    final Document document = results.get(0);
    document.lock();
    this.em.merge(document);
    return document;
}

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

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

From source file:org.tsugi.jpa.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 w w  w. ja va  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, r"); //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"); // 18
    //, r.resultId, r.sourcedid, r.grade"); // 3

    if (includesService) {
        sb.append(", s"); //, s.serviceId, s.serviceKey AS service"); // 2
    }
    /*
    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
            "LEFT JOIN u.results r " // LtiResultEntity
    );

    if (includesService) {
        sb.append(" LEFT JOIN k.services s ON s.serviceSha256 = :service"); // LtiServiceEntity
    }
    /*
    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();
    System.out.println("sql=" + sql);
    this.sqlQuery = sql;
    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));
    }
    @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];
        System.out.println("Secret = " + key.getSecret());
        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 (row.length > 5)
            result = (LtiResultEntity) row[5];
        if (includesService) {
            if (row.length > 6)
                service = (LtiServiceEntity) row[6];
        }

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

public UserActionList getUserActionsByTypeAndMediapackageIdByDate(String type, String mediapackageId,
        int offset, int limit) {
    UserActionList result = new UserActionListImpl();

    result.setTotal(getTotal(type, mediapackageId));
    result.setOffset(offset);//from  w  w w  .  ja v a2  s  .  com
    result.setLimit(limit);

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

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

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

public UserActionList getUserActionsByTypeAndMediapackageIdByDescendingDate(String type, String mediapackageId,
        int offset, int limit) {
    UserActionList result = new UserActionListImpl();
    result.setTotal(getTotal(type, mediapackageId));
    result.setOffset(offset);//from ww  w.j  a v  a2 s .  c o m
    result.setLimit(limit);

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

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