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:org.kuali.rice.krad.data.jpa.NativeJpaQueryTranslator.java

/**
 * {@inheritDoc}//from  w w w.  java  2s.com
 */
@Override
public void convertQueryFlags(QueryByCriteria qbc, TypedQuery query) {
    final int startAtIndex = qbc.getStartAtIndex() != null ? qbc.getStartAtIndex() : 0;

    query.setFirstResult(startAtIndex);

    if (qbc.getMaxResults() != null) {
        //not subtracting one from MaxResults in order to retrieve
        //one extra row so that the MoreResultsAvailable field can be set
        query.setMaxResults(qbc.getMaxResults());
    }
}

From source file:org.medici.bia.dao.image.ImageDAOJpaImpl.java

/**
 * {@inheritDoc}//  w  ww .j  a  v a 2s.c  o  m
 */
@SuppressWarnings("rawtypes")
@Override
public Page findImages(Integer volNum, String volLetExt, PaginationFilter paginationFilter)
        throws PersistenceException {
    // Create criteria objects
    CriteriaBuilder criteriaBuilder = getEntityManager().getCriteriaBuilder();

    Page page = new Page(paginationFilter);

    if (paginationFilter.getTotal() == null) {
        CriteriaQuery<Long> criteriaQueryCount = criteriaBuilder.createQuery(Long.class);
        Root<Image> rootCount = criteriaQueryCount.from(Image.class);
        criteriaQueryCount.select(criteriaBuilder.count(rootCount));

        // Define predicate's elements
        ParameterExpression<Integer> parameterVolNum = criteriaBuilder.parameter(Integer.class, "volNum");
        ParameterExpression<String> parameterVolLeText = StringUtils.isEmpty("volLetExt") ? null
                : criteriaBuilder.parameter(String.class, "volLetExt");

        criteriaQueryCount
                .where(criteriaBuilder.and(criteriaBuilder.equal(rootCount.get("volNum"), parameterVolNum),
                        StringUtils.isEmpty(volLetExt) ? criteriaBuilder.isNull(rootCount.get("volLetExt"))
                                : criteriaBuilder.equal(rootCount.get("volLetExt"), parameterVolLeText)));

        TypedQuery typedQueryCount = getEntityManager().createQuery(criteriaQueryCount);
        typedQueryCount.setParameter("volNum", volNum);
        if (!StringUtils.isEmpty(volLetExt)) {
            typedQueryCount.setParameter("volLetExt", volLetExt);
        }
        page.setTotal(new Long((Long) typedQueryCount.getSingleResult()));
    }

    CriteriaQuery<Image> criteriaQuery = criteriaBuilder.createQuery(Image.class);
    Root<Image> root = criteriaQuery.from(Image.class);

    // Define predicate's elements
    ParameterExpression<Integer> parameterVolNum = criteriaBuilder.parameter(Integer.class, "volNum");
    ParameterExpression<String> parameterVolLeText = StringUtils.isEmpty("volLetExt") ? null
            : criteriaBuilder.parameter(String.class, "volLetExt");

    //We need to duplicate predicates beacause they are link to Root element
    criteriaQuery.where(criteriaBuilder.and(criteriaBuilder.equal(root.get("volNum"), parameterVolNum),
            StringUtils.isEmpty(volLetExt) ? criteriaBuilder.isNull(root.get("volLetExt"))
                    : criteriaBuilder.equal(root.get("volLetExt"), parameterVolLeText)));

    // Set values in predicate's elements  
    TypedQuery<Image> typedQuery = getEntityManager().createQuery(criteriaQuery);
    typedQuery.setParameter("volNum", volNum);
    if (!StringUtils.isEmpty(volLetExt)) {
        typedQuery.setParameter("volLetExt", volLetExt);
    }

    //Pagination will work with index [1 ... total] and not [0 ... total1-] 
    typedQuery.setFirstResult(paginationFilter.getFirstRecord() - 1);
    typedQuery.setMaxResults(paginationFilter.getLength());
    page.setList(typedQuery.getResultList());

    return page;
}

From source file:org.medici.bia.dao.volume.VolumeDAOJpaImpl.java

/**
 * {@inheritDoc}//from   ww w .  j  av a  2  s . co m
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
@Override
public Page searchVolumes(String text, PaginationFilter paginationFilter) throws PersistenceException {
    // Create criteria objects
    CriteriaBuilder criteriaBuilder = getEntityManager().getCriteriaBuilder();

    Page page = new Page(paginationFilter);

    if (paginationFilter.getTotal() == null) {
        CriteriaQuery<Long> criteriaQueryCount = criteriaBuilder.createQuery(Long.class);
        Root<Volume> rootCount = criteriaQueryCount.from(Volume.class);
        criteriaQueryCount.select(criteriaBuilder.count(rootCount));

        List<Predicate> predicates = new ArrayList<Predicate>();
        predicates.add(
                criteriaBuilder.like((Expression) rootCount.get("serieList").get("title"), "%" + text + "%"));
        predicates.add(criteriaBuilder.like((Expression) rootCount.get("serieList").get("subTitle1"),
                "%" + text + "%"));
        predicates.add(criteriaBuilder.like((Expression) rootCount.get("serieList").get("subTitle2"),
                "%" + text + "%"));
        predicates.add(criteriaBuilder.like((Expression) rootCount.get("orgNotes"), "%" + text + "%"));
        predicates.add(criteriaBuilder.like((Expression) rootCount.get("recips"), "%" + text + "%"));
        predicates.add(criteriaBuilder.like((Expression) rootCount.get("researcher"), "%" + text + "%"));
        predicates.add(criteriaBuilder.like((Expression) rootCount.get("senders"), "%" + text + "%"));

        //If we omiss criteriaBuilder.or every predicate is in conjunction with others  
        criteriaQueryCount.where(criteriaBuilder.or(predicates.toArray(new Predicate[] {})));

        TypedQuery typedQueryCount = getEntityManager().createQuery(criteriaQueryCount);
        page.setTotal(new Long((Long) typedQueryCount.getSingleResult()));
    }

    CriteriaQuery<Volume> criteriaQuery = criteriaBuilder.createQuery(Volume.class);
    Root<Volume> root = criteriaQuery.from(Volume.class);

    //We need to duplicate predicates beacause they are link to Root element
    List<Predicate> predicates = new ArrayList<Predicate>();
    predicates.add(criteriaBuilder.like((Expression) root.get("serieList").get("title"), "%" + text + "%"));
    predicates.add(criteriaBuilder.like((Expression) root.get("serieList").get("subTitle1"), "%" + text + "%"));
    predicates.add(criteriaBuilder.like((Expression) root.get("serieList").get("subTitle2"), "%" + text + "%"));
    predicates.add(criteriaBuilder.like((Expression) root.get("orgNotes"), "%" + text + "%"));
    predicates.add(criteriaBuilder.like((Expression) root.get("recips"), "%" + text + "%"));
    predicates.add(criteriaBuilder.like((Expression) root.get("researcher"), "%" + text + "%"));
    predicates.add(criteriaBuilder.like((Expression) root.get("senders"), "%" + text + "%"));

    //If we omiss criteriaBuilder.or every predicate is in conjunction with others  
    criteriaQuery.where(criteriaBuilder.or(predicates.toArray(new Predicate[] {})));
    criteriaQuery.orderBy(criteriaBuilder.asc(root.get("summaryId")));

    // Set values in predicate's elements  
    TypedQuery<Volume> typedQuery = getEntityManager().createQuery(criteriaQuery);
    typedQuery.setFirstResult(paginationFilter.getFirstRecord());
    typedQuery.setMaxResults(paginationFilter.getLength());
    page.setList(typedQuery.getResultList());

    return page;
}

From source file:org.olat.core.util.mail.manager.MailManagerImpl.java

/**
 * Load all mails with the identity as from, mail which are not deleted
 * for this user. Recipients are loaded.
 * @param from/*from  w ww .jav a 2s.c  o m*/
 * @param firstResult
 * @param maxResults
 * @return
 */
@Override
public List<DBMailLight> getOutbox(Identity from, int firstResult, int maxResults, boolean fetchRecipients) {
    StringBuilder sb = new StringBuilder();
    sb.append("select distinct(mail) from ").append(DBMailLightImpl.class.getName()).append(" mail")
            .append(" inner join fetch mail.from fromRecipient")
            .append(" inner join fromRecipient.recipient fromRecipientIdentity").append(" inner join ")
            .append(fetchRecipients ? "fetch" : "").append(" mail.recipients recipient").append(" inner join ")
            .append(fetchRecipients ? "fetch" : "").append(" recipient.recipient recipientIdentity")
            .append(" where fromRecipientIdentity.key=:fromKey and fromRecipient.deleted=false and recipientIdentity.key!=:fromKey")
            .append(" order by mail.creationDate desc");

    TypedQuery<DBMailLight> query = dbInstance.getCurrentEntityManager()
            .createQuery(sb.toString(), DBMailLight.class).setParameter("fromKey", from.getKey());
    if (maxResults > 0) {
        query.setMaxResults(maxResults);
    }
    if (firstResult > 0) {
        query.setFirstResult(firstResult);
    }
    List<DBMailLight> mails = query.getResultList();
    return mails;
}

From source file:org.olat.core.util.mail.manager.MailManagerImpl.java

/**
 * Load all mails with the identity as recipient, only mails which are not deleted
 * for this user. Recipients are NOT loaded if not explicitly wanted!
 * @param identity/*  www.  j ava 2  s .  co  m*/
 * @param unreadOnly
 * @param fetchRecipients
 * @param from
 * @param firstResult
 * @param maxResults
 * @return
 */
@Override
public List<DBMailLight> getInbox(Identity identity, Boolean unreadOnly, Boolean fetchRecipients, Date from,
        int firstResult, int maxResults) {
    StringBuilder sb = new StringBuilder();
    String fetchOption = (fetchRecipients != null && fetchRecipients.booleanValue()) ? "fetch" : "";
    sb.append("select mail from ").append(DBMailLightImpl.class.getName()).append(" mail")
            .append(" inner join fetch ").append(" mail.from fromRecipient").append(" inner join ")
            .append(fetchOption).append(" mail.recipients recipient").append(" inner join ").append(fetchOption)
            .append(" recipient.recipient recipientIdentity")
            .append(" where recipientIdentity.key=:recipientKey and recipient.deleted=false");
    if (unreadOnly != null && unreadOnly.booleanValue()) {
        sb.append(" and recipient.read=false");
    }
    if (from != null) {
        sb.append(" and mail.creationDate>=:from");
    }
    sb.append(" order by mail.creationDate desc");

    TypedQuery<DBMailLight> query = dbInstance.getCurrentEntityManager()
            .createQuery(sb.toString(), DBMailLight.class).setParameter("recipientKey", identity.getKey());
    if (maxResults > 0) {
        query.setMaxResults(maxResults);
    }
    if (firstResult > 0) {
        query.setFirstResult(firstResult);
    }
    if (from != null) {
        query.setParameter("from", from, TemporalType.TIMESTAMP);
    }

    List<DBMailLight> mails = query.getResultList();
    return mails;
}

From source file:org.orcid.persistence.dao.impl.OrgDisambiguatedDaoImpl.java

@Override
public List<OrgDisambiguatedEntity> getChunk(int firstResult, int maxResults) {
    // Order by id so that we can page through in a predictable way
    TypedQuery<OrgDisambiguatedEntity> query = entityManager
            .createQuery("from OrgDisambiguatedEntity order by id", OrgDisambiguatedEntity.class);
    query.setFirstResult(firstResult);
    query.setMaxResults(maxResults);/*  w  w w  . j  a v  a  2s .c  o m*/
    return query.getResultList();
}

From source file:org.orcid.persistence.dao.impl.OrgDisambiguatedDaoImpl.java

@Override
public List<OrgDisambiguatedEntity> findOrgsByIndexingStatus(IndexingStatus indexingStatus, int firstResult,
        int maxResult) {
    TypedQuery<OrgDisambiguatedEntity> query = entityManager.createQuery(
            "from OrgDisambiguatedEntity where indexingStatus = :indexingStatus", OrgDisambiguatedEntity.class);
    query.setParameter("indexingStatus", indexingStatus);
    query.setFirstResult(0);
    query.setMaxResults(maxResult);//  www . j  a v  a  2s .  com
    return query.getResultList();
}

From source file:org.seedstack.i18n.rest.internal.infrastructure.jpa.KeysQuery.java

@Override
public List<Key> getResultList(Range range) {
    if (!predicates.isEmpty()) {
        selectQuery.where(criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()])));
    }//from  www.  ja  v a 2  s  . co  m

    // Get all the keys with their default translation
    TypedQuery<Key> query = entityManager.createQuery(selectQuery);
    if (range != null) {
        query.setFirstResult((int) range.getOffset());
        query.setMaxResults((int) range.getSize());
    }
    return query.getResultList();
}

From source file:org.seedstack.samples.store.infrastructure.jpa.JpaCategoryRepresentationFinder.java

@Override
protected List<CategoryRepresentation> computeResultList(Range range, Map<String, Object> criteria) {

    TypedQuery<CategoryRepresentation> query = entityManager.createQuery(
            "select new " + CategoryRepresentation.class.getName() + " (c.categoryId, c.name,c.urlImg) from "
                    + " Category c" + whereCategoryClause("c", criteria) + " order by c.categoryId",
            CategoryRepresentation.class);

    query.setFirstResult((int) range.getOffset());
    query.setMaxResults((int) range.getSize());
    return query.getResultList();
}

From source file:org.seedstack.samples.store.infrastructure.jpa.JpaProductRepresentationFinder.java

@Override
protected List<ProductRepresentation> computeResultList(Range range, Map<String, Object> criteria) {
    TypedQuery<ProductRepresentation> query = entityManager.createQuery("select new "
            + ProductRepresentation.class.getName()
            + "(p.entityId, p.designation, p.summary, p.details, p.picture, p.price,p.categoryId,cat.name)"
            + " from Product p,Category cat where p.categoryId=cat.categoryId " + getWhereClauseEnd()
            + " order by p.categoryId, p.entityId", ProductRepresentation.class);
    query.setFirstResult((int) range.getOffset());
    query.setMaxResults((int) range.getSize());
    return query.getResultList();
}