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.syncope.core.persistence.dao.impl.ReportDAOImpl.java

@Override
public List<Report> findAll(final int page, final int itemsPerPage) {
    final Query query = entityManager.createQuery("SELECT e FROM " + Report.class.getSimpleName() + " e");

    query.setFirstResult(itemsPerPage * (page <= 0 ? 0 : page - 1));

    if (itemsPerPage > 0) {
        query.setMaxResults(itemsPerPage);
    }//from   www . j  av a  2  s .  co m

    return query.getResultList();
}

From source file:org.eurekastreams.server.persistence.mappers.stream.GetFlaggedActivitiesForOrganization.java

/**
 * Get all flagged activities posted directly under an organization.
 *
 * @param inRequest// w w  w . j av  a 2s . co  m
 *            the request containing the organization and requesting user
 * @return a paged set of ActivityDTOs
 */
@Override
@SuppressWarnings("unchecked")
public PagedSet<ActivityDTO> execute(final GetFlaggedActivitiesByOrgRequest inRequest) {
    if (inRequest.getRequestingUserAccountId() == null) {
        log.error("Missing requesting user account.");
        throw new RuntimeException("Missing requesting user account.");
    }

    // get the total number of flagged activities
    Long flaggedActivityCount = (Long) buildQuery("count(*)", inRequest.getOrganizationId()).getSingleResult();

    List<ActivityDTO> activities;
    if (flaggedActivityCount > 0) {
        log.info("Found " + flaggedActivityCount
                + " flagged activity ids - passing them to the bulk activity mapper for ActivityDTOs.");

        Query q = buildQuery("id", inRequest.getOrganizationId());
        q.setFirstResult(inRequest.getStartIndex());
        q.setMaxResults(inRequest.getEndIndex() - inRequest.getStartIndex() + 1);
        List<Long> activityIds = q.getResultList();

        activities = activitiesMapper.execute(activityIds);
    } else {
        log.info("Found no flagged activity ids.");
        activities = new ArrayList<ActivityDTO>();
    }
    return new PagedSet<ActivityDTO>(inRequest.getStartIndex(), inRequest.getEndIndex(),
            flaggedActivityCount.intValue(), activities);
}

From source file:org.oscarehr.common.dao.ConsultResponseDao.java

@SuppressWarnings("unchecked")
public List<Object[]> search(ConsultationResponseSearchFilter filter) {
    String sql = this.getSearchQuery(filter, false);
    logger.debug("sql=" + sql);

    Query query = entityManager.createQuery(sql);
    query.setFirstResult(filter.getStartIndex());
    query.setMaxResults(filter.getNumToReturn());
    return query.getResultList();
}

From source file:play.modules.resteasy.crud.PagedQuery.java

public List<T> getResultList() {
    Query query = getQuery();
    if (start != null)
        query.setFirstResult(start.intValue());
    if (limit != null)
        query.setMaxResults(limit.intValue());
    return query.getResultList();
}

From source file:me.doshou.admin.monitor.web.controller.JPAQLExecutorController.java

@PageableDefaults(pageNumber = 0, value = 10)
@RequestMapping(value = "/ql", method = RequestMethod.POST)
public String executeQL(final @RequestParam("ql") String ql, final Model model, final Pageable pageable) {

    model.addAttribute("sessionFactory", HibernateUtils.getSessionFactory(em));

    try {/*from  ww  w . j a va 2s .co m*/
        new TransactionTemplate(transactionManager).execute(new TransactionCallback<Void>() {
            @Override
            public Void doInTransaction(TransactionStatus status) {
                //1?ql
                try {
                    Query query = em.createQuery(ql);
                    int updateCount = query.executeUpdate();
                    model.addAttribute("updateCount", updateCount);
                    return null;
                } catch (Exception e) {
                }
                //2 ?ql
                String findQL = ql;
                String alias = QueryUtils.detectAlias(findQL);
                if (StringUtils.isEmpty(alias)) {
                    Pattern pattern = Pattern.compile("^(.*\\s*from\\s+)(.*)(\\s*.*)",
                            Pattern.MULTILINE | Pattern.CASE_INSENSITIVE);
                    findQL = pattern.matcher(findQL).replaceFirst("$1$2 o $3");
                }
                String countQL = QueryUtils.createCountQueryFor(findQL);
                Query countQuery = em.createQuery(countQL);
                Query findQuery = em.createQuery(findQL);
                findQuery.setFirstResult(pageable.getOffset());
                findQuery.setMaxResults(pageable.getPageSize());

                Page page = new PageImpl(findQuery.getResultList(), pageable,
                        (Long) countQuery.getSingleResult());

                model.addAttribute("resultPage", page);
                return null;
            }
        });
    } catch (Exception e) {
        StringWriter sw = new StringWriter();
        e.printStackTrace(new PrintWriter(sw));
        model.addAttribute(Constants.ERROR, sw.toString());
    }

    return showQLForm();
}

From source file:com.impetus.kundera.rest.common.EntityUtils.java

/**
 * @param queryString//from ww w.j  a v  a  2  s . co m
 * @param q
 * @param em
 */
public static void setObjectQueryParameters(String queryString, String parameterString, Query q,
        EntityManager em, String mediaType) {
    MetamodelImpl metamodel = (MetamodelImpl) em.getEntityManagerFactory().getMetamodel();

    if (parameterString == null || parameterString.isEmpty()) {
        return;
    }

    Map<String, String> paramsMap = new HashMap<String, String>();
    ObjectMapper mapper = new ObjectMapper();

    try {
        paramsMap = mapper.readValue(parameterString, new TypeReference<HashMap<String, String>>() {
        });
        KunderaQuery kq = ((QueryImpl) q).getKunderaQuery();
        Set<Parameter<?>> parameters = kq.getParameters();
        for (String paramName : paramsMap.keySet()) {
            String value = paramsMap.get(paramName);

            if (paramName.equalsIgnoreCase("firstResult")) {
                q.setFirstResult(Integer.parseInt(value));

            } else if (paramName.equalsIgnoreCase("maxResult")) {
                q.setMaxResults(Integer.parseInt(value));

            } else if (StringUtils.isNumeric(paramName)) {
                for (Parameter param : parameters) {
                    if (param.getPosition() == Integer.parseInt(paramName)) {

                        Class<?> paramClass = param.getParameterType();
                        Object paramValue = null;
                        if (metamodel.isEmbeddable(paramClass)) {
                            paramValue = JAXBUtils.toObject(StreamUtils.toInputStream(value), paramClass,
                                    mediaType);

                        } else {
                            PropertyAccessor accessor = PropertyAccessorFactory.getPropertyAccessor(paramClass);
                            paramValue = accessor.fromString(paramClass, value);
                        }

                        q.setParameter(Integer.parseInt(paramName), paramValue);
                        break;
                    }
                }
            } else {
                for (Parameter param : parameters) {
                    if (param.getName().equals(paramName)) {

                        Class<?> paramClass = param.getParameterType();
                        Object paramValue = null;

                        if (metamodel.isEmbeddable(paramClass)) {
                            paramValue = JAXBUtils.toObject(StreamUtils.toInputStream(value), paramClass,
                                    mediaType);

                        } else {
                            PropertyAccessor accessor = PropertyAccessorFactory.getPropertyAccessor(paramClass);
                            paramValue = accessor.fromString(paramClass, value);
                        }
                        q.setParameter(paramName, paramValue);
                        break;
                    }
                }

            }
        }

    } catch (JsonParseException e) {
        log.error(e.getMessage());
    } catch (JsonMappingException e) {
        log.error(e.getMessage());
    } catch (IOException e) {
        log.error(e.getMessage());
    }
}

From source file:sf.wicketlearningapplication.persistence.BugDao.java

@SuppressWarnings("unchecked")
public List<Bug> findAll(final User owner, final String orderBy, final boolean isAscending,
        final int startPosition, final int maxResult) {
    final boolean filterByOwner = owner != null && !owner.isAdmin();
    em.getTransaction().begin();//from   w w  w . j  a  va 2s.  co  m
    List<Bug> bugs = null;
    String hql = "from Bug b";
    if (filterByOwner) {
        hql = hql + " where b.owner = :owner";
    }
    if (!StringUtils.isBlank(orderBy)) {
        hql = hql + " order by " + orderBy + " " + (isAscending ? "asc" : "desc");
    }
    final Query query = em.createQuery(hql);
    if (filterByOwner) {
        query.setParameter("owner", owner);
    }
    query.setFirstResult(startPosition);
    query.setMaxResults(maxResult);
    bugs = query.getResultList();
    em.getTransaction().commit();

    return bugs;
}

From source file:org.oscarehr.ticklers.service.TicklersDao.java

@SuppressWarnings("unchecked")
public List<Tickler> getTicklers(TicklerQuery ticklerQuery) {
    StringBuilder sql = this.generateQuery(ticklerQuery, false);
    Query query = entityManager.createQuery(sql.toString());
    query.setFirstResult(ticklerQuery.getStart());
    query.setMaxResults(ticklerQuery.getLimit());
    return query.getResultList();
}

From source file:org.zkbase.dao.BasicDao.java

/**
 * Retrieves a paged query.// w ww. j  a va  2 s. c om
 */
@SuppressWarnings("unchecked")
public <T> List<T> find(String queryString, int firstResult, int maxResults, Object... params) {
    Query query = entityManager.createQuery(queryString);
    query.setFirstResult(firstResult);
    query.setMaxResults(maxResults);
    setParameters(query, params);
    return query.getResultList();
}

From source file:org.zkbase.dao.BasicDao.java

/**
 * Retrieves a non-paged query/*from www . j a  v  a  2  s.  c o m*/
 */
@SuppressWarnings("unchecked")
public <T> List<T> findNamedQuery(final String namedQuery, int firstResult, int maxResult, Object... params) {

    Query query = entityManager.createNamedQuery(namedQuery);
    query.setFirstResult(firstResult);
    query.setMaxResults(maxResult);
    setParameters(query, params);
    return query.getResultList();
}