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: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  va2s. c  om*/
    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.easyj.orm.jpa.JPAEntityDao.java

/**
 * Adiciona mapa de parmetros a query//from w  ww. j  a  v a  2  s  .c o m
 *
 * @param q Query que requer parmetros
 * @param params Mapa de parmetros
 * @return true se todos os parmetros foram adicionados, false se houve erro em algum parmetro
 */
private boolean setParameters(Query q, Map<String, Object> params) {
    if (q != null && params != null) {
        Integer maxResults = (Integer) params.remove(EntityService.PARAM_MAX_RESULTS);
        if (maxResults != null && maxResults > 0) {
            q.setMaxResults(maxResults.intValue());
        }

        Integer startPosition = (Integer) params.remove(EntityService.PARAM_START_POSITION);
        if (startPosition != null && startPosition > -1) {
            q.setFirstResult(startPosition.intValue());
        }

        for (Entry<String, Object> o : params.entrySet()) {
            try {
                q.setParameter(o.getKey().trim(), o.getValue());
            } catch (IllegalArgumentException ex) {
                logger.debug("Illegal Query Parameter", ex);
                return false;
            }
        }
    }
    return true;
}

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);
    q.setMaxResults(maxResults);// www .j a v a  2s.  c  om
    return q.getResultList();
}

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

/**
 * {@inheritDoc}//  w  w w . jav  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.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  .j  a v  a2s. 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

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

    result.setTotal(getTotal(type, mediapackageId));
    result.setOffset(offset);//ww  w . jav a2 s.c  o  m
    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);//  w ww.  jav  a2s. co 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();
        }
    }
}

From source file:eu.forgestore.ws.impl.FStoreJpaController.java

public List<Widget> readWidgetMetadata(Long categoryid, int firstResult, int maxResults) {
    EntityManager entityManager = entityManagerFactory.createEntityManager();
    Query q;

    if ((categoryid != null) && (categoryid >= 0))
        q = entityManager//from w ww  . ja  v a  2 s  . c  o  m
                .createQuery("SELECT a FROM Widget a WHERE a.categories.id=" + categoryid + " ORDER BY a.id");
    else
        q = entityManager.createQuery("SELECT a FROM Widget a ORDER BY a.id");
    q.setFirstResult(firstResult);
    q.setMaxResults(maxResults);
    return q.getResultList();
}

From source file:eu.forgestore.ws.impl.FStoreJpaController.java

public List<Course> readCoursesMetadata(Long categoryid, int firstResult, int maxResults) {
    EntityManager entityManager = entityManagerFactory.createEntityManager();
    Query q;

    if ((categoryid != null) && (categoryid >= 0))
        q = entityManager//from www .jav  a  2s .co  m
                .createQuery("SELECT a FROM Course a WHERE a.categories.id=" + categoryid + " ORDER BY a.id");
    else
        q = entityManager.createQuery("SELECT a FROM Course a ORDER BY a.id");
    q.setFirstResult(firstResult);
    q.setMaxResults(maxResults);
    return q.getResultList();
}

From source file:eu.forgestore.ws.impl.FStoreJpaController.java

@SuppressWarnings("unchecked")
public List<Product> readProducts(Long categoryid, int firstResult, int maxResults) {
    EntityManager entityManager = entityManagerFactory.createEntityManager();
    Query q;

    if ((categoryid != null) && (categoryid >= 0))
        q = entityManager//from ww w .j a v  a 2  s  .  co  m
                .createQuery("SELECT a FROM Product a WHERE a.category.id=" + categoryid + " ORDER BY a.id");
    else
        q = entityManager.createQuery("SELECT a FROM Product a ORDER BY a.id");

    q.setFirstResult(firstResult);
    q.setMaxResults(maxResults);
    return q.getResultList();
}