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.music.dao.PieceDao.java

@SuppressWarnings("rawtypes")
public Map<Piece, Integer> getTopRecentPieces(int page, int pageSize, DateTime minusWeeks) {
    TypedQuery<List> query = getEntityManager().createQuery(
            "SELECT new list(ev.piece, COUNT(ev) AS cnt) FROM PieceEvaluation ev WHERE ev.dateTime > :threshold AND ev.piece.likes > 0 GROUP BY ev.piece ORDER BY cnt DESC, ev.dateTime DESC",
            List.class);
    query.setParameter("threshold", minusWeeks);
    query.setFirstResult(page * pageSize);
    query.setMaxResults(pageSize);//from w  w  w  .  ja v a  2 s. c om

    Map<Piece, Integer> result = new LinkedHashMap<>();
    for (List<?> list : query.getResultList()) {
        result.put((Piece) list.get(0), ((Long) list.get(1)).intValue());
    }
    return result;
}

From source file:com.sishuok.es.common.repository.support.SimpleBaseRepository.java

/**
 * Reads the given {@link javax.persistence.TypedQuery} into a {@link org.springframework.data.domain.Page} applying the given {@link org.springframework.data.domain.Pageable} and
 * {@link org.springframework.data.jpa.domain.Specification}.
 *
 * @param query    must not be {@literal null}.
 * @param spec     can be {@literal null}.
 * @param pageable can be {@literal null}.
 * @return/*from   www  .ja v a 2  s.  c om*/
 */
private Page<M> readPage(TypedQuery<M> query, Pageable pageable, Specification<M> spec) {

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

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

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

From source file:com.luna.common.repository.support.SimpleBaseRepository.java

/**
 * Reads the given {@link javax.persistence.TypedQuery} into a {@link org.springframework.data.domain.Page} applying the given {@link org.springframework.data.domain.Pageable} and
 * {@link org.springframework.data.jpa.domain.Specification}.
 *
 * @param query    must not be {@literal null}.
 * @param spec     can be {@literal null}.
 * @param pageable can be {@literal null}.
 * @return//from www .  ja  va2  s  .com
 */
protected Page<M> readPage(TypedQuery<M> query, Pageable pageable, Specification<M> spec) {

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

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

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

From source file:com.zero.dao.impl.BaseDaoImpl.java

protected Page<T> findPage(CriteriaQuery<T> criteriaQuery, Pageable pageable) {
    Assert.notNull(criteriaQuery);/*  w  ww  .ja va2s  .co m*/
    Assert.notNull(criteriaQuery.getSelection());
    Assert.notEmpty(criteriaQuery.getRoots());

    if (pageable == null) {
        pageable = new Pageable();
    }
    // CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    // Root<T> root = getRoot(criteriaQuery);
    addRestrictions(criteriaQuery, pageable);
    // addOrders(criteriaQuery, pageable);
    // 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)));
    // }
    // }
    long total = count(criteriaQuery, null);
    int totalPages = (int) Math.ceil(total / (double) pageable.getPageSize());
    if (totalPages < pageable.getPageNumber()) {
        pageable.setPageNumber(totalPages);
    }
    TypedQuery<T> query = entityManager.createQuery(criteriaQuery).setFlushMode(FlushModeType.COMMIT);
    query.setFirstResult((pageable.getPageNumber() - 1) * pageable.getPageSize());
    query.setMaxResults(pageable.getPageSize());
    return new Page<T>(query.getResultList(), total, pageable);
}

From source file:cn.guoyukun.spring.jpa.repository.support.SimpleBaseRepository.java

/**
 * Reads the given {@link javax.persistence.TypedQuery} into a {@link org.springframework.data.domain.Page} applying the given {@link org.springframework.data.domain.Pageable} and
 * {@link org.springframework.data.jpa.domain.Specification}.
 *
 * @param query    must not be {@literal null}.
 * @param spec     can be {@literal null}.
 * @param pageable can be {@literal null}.
 * @return//from w  w  w  . j  a  va2 s  . c om
 */
@Override
protected Page<M> readPage(TypedQuery<M> query, Pageable pageable, Specification<M> spec) {

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

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

    return new PageImpl4jqgrid<M>(content, pageable, total);
}

From source file:com.zero.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 .jav  a 2s .c om
    Assert.notNull(criteriaQuery.getSelection());
    Assert.notEmpty(criteriaQuery.getRoots());

    addRestrictions(criteriaQuery, filters);
    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.creditcloud.common.entities.dao.AbstractReadDAO.java

/**
 * list entity by CriteriaInfo// ww  w. ja  v  a2 s  .c  om
 *
 * @param criteriaInfo
 * @return PagedResult
 */
public PagedResult<T> list(CriteriaInfo criteriaInfo) {
    EntityManager em = getEntityManager();
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery cq = cb.createQuery(entityClass);
    Root<T> userRoot = cq.from(entityClass);
    cq.select(userRoot);
    ParamInfo paramInfo = criteriaInfo.getParamInfo();
    PageInfo pageInfo = criteriaInfo.getPageInfo();
    SortInfo sortInfo = criteriaInfo.getSortInfo();

    //build query for paramInfo
    if (paramInfo != null) {
        Set<Predicate> andCriteria = new HashSet();
        Set<Predicate> orCriteria = new HashSet();

        for (ParamItem item : paramInfo.getParamItems()) {
            Predicate predicate;
            if (item.getValue() instanceof String) {
                //fuzy search for string
                String regExp = "%" + item.getValue() + "%";
                predicate = cb.like((Expression) (userRoot.get(item.getFieldName())), regExp);
            } else {
                predicate = cb.equal((userRoot.get(item.getFieldName())), item.getValue());
            }

            switch (item.getOperator()) {
            case AND:
                andCriteria.add(predicate);
                break;
            case OR:
                orCriteria.add(predicate);
                break;
            }
        }
        if (orCriteria.size() > 0) {
            Predicate or = cb.or(orCriteria.toArray(new Predicate[orCriteria.size()]));
            andCriteria.add(or);
        }
        if (andCriteria.size() > 0) {
            Predicate and = cb.and(andCriteria.toArray(new Predicate[andCriteria.size()]));
            cq.where(and);
        }
    }

    //build query for sortInfo
    Set<Order> orderPredicate = new HashSet<>();
    if (sortInfo != null) {
        for (SortItem item : sortInfo.getSortItems()) {
            if (item.isDescending()) {
                orderPredicate.add(cb.desc(userRoot.get(item.getFieldName())));
            } else {
                orderPredicate.add(cb.asc(userRoot.get(item.getFieldName())));
            }
        }
    }
    if (orderPredicate.size() > 0) {
        cq.orderBy(orderPredicate.toArray(new Order[orderPredicate.size()]));
    }

    TypedQuery<T> query = em.createQuery(cq);
    //set result range
    if (pageInfo != null) {
        query.setFirstResult(pageInfo.getOffset());
        query.setMaxResults(pageInfo.getSize());
    }

    int totalSize;
    if (paramInfo != null && paramInfo.getParamItems().size() > 0) {
        totalSize = count(paramInfo);
    } else {
        totalSize = count();
    }

    return new PagedResult(query.getResultList(), totalSize);
}

From source file:net.nan21.dnet.core.presenter.service.asgn.AbstractAsgnService.java

/**
 * // w  ww . j  av a2  s  . c om
 * @param selectionId
 * @param filter
 * @param params
 * @param builder
 * @return
 * @throws Exception
 */
public List<M> findLeft(String selectionId, F filter, P params, IQueryBuilder<M, F, P> builder)
        throws Exception {
    QueryBuilderWithJpql<M, F, P> bld = (QueryBuilderWithJpql<M, F, P>) builder;

    bld.addFilterCondition(" e.clientId = :clientId and e." + this.ctx.getLeftPkField()
            + " not in (select x.itemId from TempAsgnLine x where x.selectionId = :selectionId)");

    bld.setFilter(filter);
    bld.setParams(params);

    List<M> result = new ArrayList<M>();
    TypedQuery<E> q = bld.createQuery(this.getEntityClass());
    q.setParameter("clientId", Session.user.get().getClient().getId());
    q.setParameter("selectionId", selectionId);
    List<E> list = q.setFirstResult(bld.getResultStart()).setMaxResults(bld.getResultSize()).getResultList();
    for (E e : list) {
        M m = this.getModelClass().newInstance();
        entityToModel(e, m);
        result.add(m);
    }
    return result;
}

From source file:net.nan21.dnet.core.presenter.service.asgn.AbstractAsgnService.java

/**
 * /* w  w w  . ja v  a2s. c  om*/
 * @param selectionId
 * @param filter
 * @param params
 * @param builder
 * @return
 * @throws Exception
 */
public List<M> findRight(String selectionId, F filter, P params, IQueryBuilder<M, F, P> builder)
        throws Exception {
    QueryBuilderWithJpql<M, F, P> bld = (QueryBuilderWithJpql<M, F, P>) builder;

    bld.addFilterCondition(" e.clientId = :clientId and e." + this.ctx.getLeftPkField()
            + " in (select x.itemId from TempAsgnLine x where x.selectionId = :selectionId)");
    bld.setFilter(filter);
    bld.setParams(params);

    List<M> result = new ArrayList<M>();

    TypedQuery<E> q = bld.createQuery(this.getEntityClass());
    q.setParameter("clientId", Session.user.get().getClient().getId());
    q.setParameter("selectionId", selectionId);
    List<E> list = q.setFirstResult(bld.getResultStart()).setMaxResults(bld.getResultSize()).getResultList();
    for (E e : list) {
        M m = this.getModelClass().newInstance();
        entityToModel(e, m);
        result.add(m);
    }
    return result;
}

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

protected Page<T> findPage(CriteriaQuery<T> criteriaQuery, Pageable pageable) {
    Assert.notNull(criteriaQuery);//from  w w w  .j  a  va  2  s. c o  m
    Assert.notNull(criteriaQuery.getSelection());
    Assert.notEmpty(criteriaQuery.getRoots());

    if (pageable == null) {
        pageable = new Pageable();
    }
    CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    Root<T> root = getRoot(criteriaQuery);
    addRestrictions(criteriaQuery, pageable);
    addOrders(criteriaQuery, pageable);
    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)));
        }
    }
    long total = count(criteriaQuery, null);
    int totalPages = (int) Math.ceil((double) total / (double) pageable.getPageSize());
    if (totalPages < pageable.getPageNumber()) {
        pageable.setPageNumber(totalPages);
    }
    TypedQuery<T> query = entityManager.createQuery(criteriaQuery).setFlushMode(FlushModeType.COMMIT);
    query.setFirstResult((pageable.getPageNumber() - 1) * pageable.getPageSize());
    query.setMaxResults(pageable.getPageSize());
    return new Page<T>(query.getResultList(), total, pageable);
}