Example usage for javax.persistence Query setFirstResult

List of usage examples for javax.persistence Query setFirstResult

Introduction

In this page you can find the example usage for javax.persistence Query setFirstResult.

Prototype

Query setFirstResult(int startPosition);

Source Link

Document

Set the position of the first result to retrieve.

Usage

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

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

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

private List<SyncopeUser> doSearch(final Set<Long> adminRoles, final NodeCond nodeCond, final int page,
        final int itemsPerPage) {

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

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

    // 2. take into account administrative roles
    if (queryString.charAt(0) == '(') {
        queryString.insert(0, "SELECT u.user_id FROM ");
        queryString.append(" u WHERE user_id NOT IN (");
    } else {/*  ww  w . jav  a  2s .  c om*/
        queryString.insert(0, "SELECT u.user_id FROM (");
        queryString.append(") u WHERE user_id NOT IN (");
    }
    queryString.append(getAdminRolesFilter(adminRoles)).append(")");

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

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

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

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

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

    // 5. Prepare the result (avoiding duplicates - set)
    final Set<Number> userIds = new HashSet<Number>();
    final List resultList = query.getResultList();

    //fix for HHH-5902 - bug hibernate
    if (resultList != null) {
        for (Object userId : resultList) {
            if (userId instanceof Object[]) {
                userIds.add((Number) ((Object[]) userId)[0]);
            } else {
                userIds.add((Number) userId);
            }
        }
    }

    final List<SyncopeUser> result = new ArrayList<SyncopeUser>(userIds.size());

    SyncopeUser user;
    for (Object userId : userIds) {
        user = userDAO.find(((Number) userId).longValue());
        if (user == null) {
            LOG.error("Could not find user with id {}, " + "even though returned by the native query", userId);
        } else {
            result.add(user);
        }
    }

    return result;
}

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 . jav a2s . 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: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());
    }/*from  w  ww  . ja  va2s.com*/

    @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.sofun.core.member.MemberServiceImpl.java

@SuppressWarnings("unchecked")
@Override/*  w  w w  . j  a v a 2 s .  c  om*/
public Iterator<Member> listMembers(int offset, int batchSize) {
    String queryStr = "from " + MemberImpl.class.getSimpleName() + " ORDER BY id";
    Query query = createQuery(queryStr);
    query.setFirstResult(offset);
    query.setMaxResults(batchSize);
    return query.getResultList().iterator();
}

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

@Test
public void test_paginate() {
    EntityManager entityManager = newMock(EntityManager.class);
    Query query = newMock(Query.class);
    Query query2 = newMock(Query.class);
    expect(entityManager/* w  ww  .  j  a  v  a2  s  .co m*/
            .createQuery("select root.id from corner.orm.gae.impl.TestAEntity as root  where name=:1"))
                    .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" }, null, options);
    assertFalse(((Iterator) pl.collectionObject()).hasNext());
    PaginationOptions optionsR = pl.options();
    assertEquals(1234, optionsR.getTotalRecord());
    verify();
}

From source file:com.impetus.ankush.common.dao.impl.GenericDaoJpa.java

public List<T> getAll(int start, int maxResults, String... orderBy) {
    Query query = this.entityManager.createQuery(getAllQueryString() + createOrderByClause(orderBy));

    query.setFirstResult(start);
    query.setMaxResults(maxResults);/*  w ww .  j  a v  a2  s .c o m*/

    return query.getResultList();
}

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 av a 2s .  com
@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:de.iai.ilcd.model.dao.ProcessDao.java

/**
 * Get the list of processes which have the provided direction and flow as in- or output exchange flow
 * //from   www.ja va 2  s  . co m
 * @param flowUuid
 *            uuid of flow
 * @param direction
 *            direction of flow
 * @param firstResult
 *            start index
 * @param maxResults
 *            maximum result items
 * @return list of processes which have the provided direction and flow as in- or output exchange flow
 */
@SuppressWarnings("unchecked")
public List<Process> getProcessesForExchangeFlow(String flowUuid, ExchangeDirection direction, int firstResult,
        int maxResults) {
    Query q = this.getProcessesForExchangeFlowQuery(flowUuid, direction, false);
    q.setFirstResult(firstResult);
    q.setMaxResults(maxResults);
    return q.getResultList();
}

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

/**
 * Query count from db./*from  w  ww.  j av 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();
}