Example usage for javax.persistence TypedQuery setFirstResult

List of usage examples for javax.persistence TypedQuery setFirstResult

Introduction

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

Prototype

TypedQuery<X> setFirstResult(int startPosition);

Source Link

Document

Set the position of the first result to retrieve.

Usage

From source file:com.ushahidi.swiftriver.core.api.dao.impl.JpaBucketDao.java

public List<Bucket> findAll(String searchTerm, int count, int page) {
    String qlString = "SELECT b FROM Bucket b WHERE " + "b.published = 1 "
            + "AND (b.name LIKE :term OR b.description LIKE :term " + "OR b.bucketNameCanonical LIKE :term)";

    TypedQuery<Bucket> query = em.createQuery(qlString, Bucket.class);
    query.setParameter("term", "%" + searchTerm + "%");
    query.setMaxResults(count);/*from   w  w w . ja  va  2s  . com*/
    query.setFirstResult(count * (page - 1));

    return query.getResultList();
}

From source file:no.dusken.momus.service.ArticleService.java

public List<Article> searchForArticles(ArticleSearchParams params) {
    long start = System.currentTimeMillis();

    ArticleQueryBuilder builder = new ArticleQueryBuilder(params);
    String queryText = builder.getFullQuery();
    Map<String, Object> queryParams = builder.getQueryParams();

    TypedQuery<Article> query = entityManager.createQuery(queryText, Article.class);

    for (Map.Entry<String, Object> e : queryParams.entrySet()) {
        query.setParameter(e.getKey(), e.getValue());
    }//from ww w.  j  av a  2s  .co m

    query.setMaxResults(params.getPageSize() + 1); // One extra, so searchpage can see if there is "more pages"
    query.setFirstResult(params.getStartOfPage());

    List<Article> resultList = query.getResultList();

    long end = System.currentTimeMillis();
    long timeUsed = end - start;
    logger.debug("Time spent on search: {}ms", timeUsed);
    if (timeUsed > 800) {
        logger.warn("Time spent on search high ({}ms), params were: {}", timeUsed, params);
    }

    return resultList;
}

From source file:net.groupbuy.dao.impl.BaseDaoImpl.java

protected List<T> findList(CriteriaQuery<T> criteriaQuery, Integer first, Integer count, List<Filter> filters,
        List<Order> orders) {
    Assert.notNull(criteriaQuery);/*from   w ww. j av a 2s. co  m*/
    Assert.notNull(criteriaQuery.getSelection());
    Assert.notEmpty(criteriaQuery.getRoots());

    CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    Root<T> root = getRoot(criteriaQuery);
    addRestrictions(criteriaQuery, filters);
    addOrders(criteriaQuery, orders);
    if (criteriaQuery.getOrderList().isEmpty()) {
        if (OrderEntity.class.isAssignableFrom(entityClass)) {
            criteriaQuery.orderBy(criteriaBuilder.asc(root.get(OrderEntity.ORDER_PROPERTY_NAME)));
        } else {
            criteriaQuery.orderBy(criteriaBuilder.desc(root.get(OrderEntity.CREATE_DATE_PROPERTY_NAME)));
        }
    }
    TypedQuery<T> query = entityManager.createQuery(criteriaQuery).setFlushMode(FlushModeType.COMMIT);
    if (first != null) {
        query.setFirstResult(first);
    }
    if (count != null) {
        query.setMaxResults(count);
    }
    return query.getResultList();
}

From source file:com.ushahidi.swiftriver.core.api.dao.impl.JpaRiverDao.java

public List<River> findAll(String searchTerm, int count, int page) {
    String qlString = "SELECT r FROM River r WHERE r.riverPublic = 1 " + "AND (r.riverName LIKE :term "
            + "OR r.description LIKE :term " + "OR r.riverNameCanonical LIKE :term) ";

    TypedQuery<River> query = em.createQuery(qlString, River.class);
    query.setParameter("term", "%" + searchTerm + "%");
    query.setMaxResults(count);/*from w w w  .ja  va2  s  .  c  o m*/
    query.setFirstResult(count * (page - 1));

    return query.getResultList();
}

From source file:com.uni.dao.etc.UniJpaRepository.java

/**
 * Reads the given {@link TypedQuery} into a {@link Page} applying the given {@link Pageable} and
 * {@link Specification}.//www .  ja  v  a  2s  . c o m
 * 
 * @param query must not be {@literal null}.
 * @param spec can be {@literal null}.
 * @param pageable can be {@literal null}.
 * @return
 */
private Page<T> readPage(TypedQuery<T> query, Pageable pageable, Specification<T> spec) {

    query.setFirstResult(pageable.getOffset());
    query.setMaxResults(pageable.getPageSize());

    Long total = QueryUtils.executeCountQuery(getCountQuery(spec));
    List<T> content = total > pageable.getOffset() ? query.getResultList() : Collections.<T>emptyList();

    return new PageImpl<T>(content, pageable, total);
}

From source file:org.openmeetings.app.data.basic.Fieldmanagment.java

public List<Map<String, Object>> getLabelsByLanguage(Long language_id, int start, int max) {
    try {//from ww  w  .  j a v a2 s .co m

        String sql = "select f.fieldvalues.fieldvalues_id, f.value from Fieldlanguagesvalues as f "
                + "WHERE f.language_id = :language_id ";

        TypedQuery<Object> query = em.createQuery(sql, Object.class);
        query.setParameter("language_id", language_id);
        query.setFirstResult(start);
        query.setMaxResults(max);

        String appName = cfgManagement.getAppName();
        List<Map<String, Object>> returnList = new LinkedList<Map<String, Object>>();
        for (Object fl : query.getResultList()) {
            Map<String, Object> map = new HashMap<String, Object>();
            Object[] row = (Object[]) fl;
            map.put("id", (Long) row[0]);
            map.put("value", performReplace((String) row[1], appName));
            returnList.add(map);
        }
        FieldLanguage fieldLanguage = fieldLanguageDaoImpl.getFieldLanguageById(language_id);

        log.debug("Getting Labels for Language " + fieldLanguage.getName());

        // Check for Right To Left Languages
        if (fieldLanguage.getRtl()) {
            log.debug("Language requieres RTL!");

            List<Map<String, Object>> returnRtlList = new LinkedList<Map<String, Object>>();

            for (Iterator<Map<String, Object>> iter = returnList.iterator(); iter.hasNext();) {
                Map<String, Object> remote = iter.next();

                Map<String, Object> toAdd = new HashMap<String, Object>();
                toAdd.put("id", remote.get("id"));

                String value = remote.get("value").toString();

                String[] splitted = value.split(" ");
                String reverseOrder = "";
                for (int i = splitted.length - 1; i >= 0; i--) {
                    reverseOrder += splitted[i];
                    if (splitted.length != 1) {
                        reverseOrder += " ";
                    }
                }
                log.debug("reverseOrder " + reverseOrder);
                toAdd.put("value", value);

                returnRtlList.add(toAdd);
            }

            return returnRtlList;
        } else {
            log.debug("Language doesnt requiere RTL!");

            return returnList;

        }

    } catch (Exception ex2) {
        log.error("[getLabelsByLanguage]: ", ex2);
        ex2.printStackTrace();
    }
    return null;
}

From source file:org.jdal.dao.jpa.JpaDao.java

/**
 * {@inheritDoc}/*from  w  w  w.  j  a v a2 s .  c o  m*/
 */
@SuppressWarnings("unchecked")
public <K> Page<K> getPage(Page<K> page) {

    // try named query first
    TypedQuery<K> query = getNamedQuery(page);

    if (query == null) // get query from criteria
        query = getCriteriaQuery(page);

    // add range
    query.setMaxResults(page.getPageSize());
    query.setFirstResult(page.getStartIndex());

    page.setData(query.getResultList());
    page.setPageableDataSource(((PageableDataSource<K>) this));
    return page;
}

From source file:org.terasoluna.tourreservation.domain.repository.tourinfo.TourInfoRepositoryImpl.java

protected List<TourInfo> findTourInfo(TourInfoSearchCriteria criteria, Pageable pageable) {

    String q = buildJpql(criteria.getTourDays(), criteria.getBasePrice());
    TypedQuery<TourInfo> query = entityManager.createQuery(q, TourInfo.class);

    query.setParameter("adultCount", criteria.getAdultCount());
    query.setParameter("childCount", criteria.getChildCount());
    query.setParameter("depDay", criteria.getDepDate());
    query.setParameter("depCode", criteria.getDepCode());
    query.setParameter("arrCode", criteria.getArrCode());
    if (criteria.getTourDays() != 0) {
        query.setParameter("tourDays", criteria.getTourDays());
    }/*from  w  ww .  ja  v  a2  s  .  c o  m*/
    if (criteria.getBasePrice() != 0) {
        query.setParameter("basePrice", criteria.getBasePrice());
    }

    query.setFirstResult(pageable.getOffset());
    query.setMaxResults(pageable.getPageSize());

    List<TourInfo> tourInfoList = query.getResultList();
    return tourInfoList;
}

From source file:org.openmeetings.app.data.user.Organisationmanagement.java

/**
 * /*ww w.  j  a  v a 2s  .co m*/
 * @param user_level
 * @return
 */
public List<Organisation> getOrganisations(int start, int max, String orderby, boolean asc) {
    try {
        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery<Organisation> cq = cb.createQuery(Organisation.class);
        Root<Organisation> c = cq.from(Organisation.class);
        Predicate condition = cb.equal(c.get("deleted"), "false");
        cq.where(condition);
        cq.distinct(asc);
        if (asc) {
            cq.orderBy(cb.asc(c.get(orderby)));
        } else {
            cq.orderBy(cb.desc(c.get(orderby)));
        }
        TypedQuery<Organisation> q = em.createQuery(cq);
        q.setFirstResult(start);
        q.setMaxResults(max);
        List<Organisation> ll = q.getResultList();
        return ll;
    } catch (Exception ex2) {
        log.error("[getOrganisations]", ex2);
    }
    return null;
}

From source file:com.adeptj.modules.data.jpa.core.AbstractJpaRepository.java

/**
 * {@inheritDoc}//www  .j  av  a 2  s . c  om
 */
@Override
public <T extends BaseEntity> List<T> findPaginatedRecordsByJpaQuery(CrudDTO<T> crudDTO) {
    EntityManager em = JpaUtil.createEntityManager(this.getEntityManagerFactory());
    try {
        TypedQuery<T> typedQuery = em.createQuery(crudDTO.getJpaQuery(), crudDTO.getEntity());
        JpaUtil.bindQueryParams(typedQuery, crudDTO.getPosParams());
        return typedQuery.setFirstResult(crudDTO.getStartPos()).setMaxResults(crudDTO.getMaxResult())
                .getResultList();
    } catch (Exception ex) { // NOSONAR
        throw new JpaException(ex);
    } finally {
        JpaUtil.closeEntityManager(em);
    }
}