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:gr.upatras.ece.nam.baker.impl.BakerJpaController.java

@SuppressWarnings("unchecked")
public List<BunMetadata> readBunsMetadataForOwnerID(Long ownerid, int firstResult, int maxResults) {
    EntityManager entityManager = entityManagerFactory.createEntityManager();
    //Query q = entityManager.createQuery("SELECT m FROM BunMetadata m");
    Query q;

    if ((ownerid != null) && (ownerid >= 0))
        q = entityManager//from  w  w  w .j  a  va 2  s  .  c  o m
                .createQuery("SELECT a FROM BunMetadata a WHERE a.owner.id=" + ownerid + " ORDER BY a.id");
    else
        q = entityManager.createQuery("SELECT a FROM BunMetadata a ORDER BY a.id");

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

From source file:com.haulmont.cuba.core.app.RdbmsStore.java

protected Query createQuery(EntityManager em, LoadContext context, boolean singleResult) {
    LoadContext.Query contextQuery = context.getQuery();
    if ((contextQuery == null || isBlank(contextQuery.getQueryString())) && context.getId() == null)
        throw new IllegalArgumentException("Query string or ID needed");

    DataServiceQueryBuilder queryBuilder = AppBeans.get(DataServiceQueryBuilder.NAME);
    queryBuilder.init(contextQuery == null ? null : contextQuery.getQueryString(),
            contextQuery == null ? null : contextQuery.getParameters(), context.getId(),
            context.getMetaClass());//  w w w. j av  a2s . c o  m

    queryBuilder.setSingleResult(singleResult);

    if (!context.getPrevQueries().isEmpty()) {
        log.debug("Restrict query by previous results");
        queryBuilder.restrictByPreviousResults(userSessionSource.getUserSession().getId(),
                context.getQueryKey());
    }
    Query query = queryBuilder.getQuery(em);

    if (contextQuery != null) {
        if (contextQuery.getFirstResult() != 0)
            query.setFirstResult(contextQuery.getFirstResult());
        if (contextQuery.getMaxResults() != 0)
            query.setMaxResults(contextQuery.getMaxResults());
        if (contextQuery.isCacheable()) {
            query.setCacheable(contextQuery.isCacheable());
        }
    }

    return query;
}

From source file:com.haulmont.cuba.core.app.RdbmsStore.java

@Override
public List<KeyValueEntity> loadValues(ValueLoadContext context) {
    Preconditions.checkNotNullArgument(context, "context is null");
    Preconditions.checkNotNullArgument(context.getQuery(), "query is null");

    ValueLoadContext.Query contextQuery = context.getQuery();

    if (log.isDebugEnabled())
        log.debug("query: " + (DataServiceQueryBuilder.printQuery(contextQuery.getQueryString()))
                + (contextQuery.getFirstResult() == 0 ? "" : ", first=" + contextQuery.getFirstResult())
                + (contextQuery.getMaxResults() == 0 ? "" : ", max=" + contextQuery.getMaxResults()));

    QueryParser queryParser = queryTransformerFactory.parser(contextQuery.getQueryString());
    if (!checkValueQueryPermissions(queryParser)) {
        return Collections.emptyList();
    }//from  www .  ja v  a  2 s  .c om

    List<KeyValueEntity> entities = new ArrayList<>();

    try (Transaction tx = createLoadTransaction()) {
        EntityManager em = persistence.getEntityManager(storeName);
        em.setSoftDeletion(context.isSoftDeletion());

        List<String> keys = context.getProperties();

        DataServiceQueryBuilder queryBuilder = AppBeans.get(DataServiceQueryBuilder.NAME);
        queryBuilder.init(contextQuery.getQueryString(), contextQuery.getParameters(), null,
                metadata.getClassNN(KeyValueEntity.class).getName());
        Query query = queryBuilder.getQuery(em);

        if (contextQuery.getFirstResult() != 0)
            query.setFirstResult(contextQuery.getFirstResult());
        if (contextQuery.getMaxResults() != 0)
            query.setMaxResults(contextQuery.getMaxResults());

        List resultList = query.getResultList();
        List<Integer> notPermittedSelectIndexes = getNotPermittedSelectIndexes(queryParser);
        for (Object item : resultList) {
            KeyValueEntity entity = new KeyValueEntity();
            entity.setIdName(context.getIdName());
            entities.add(entity);

            if (item instanceof Object[]) {
                Object[] row = (Object[]) item;
                for (int i = 0; i < keys.size(); i++) {
                    String key = keys.get(i);
                    if (row.length > i) {
                        if (notPermittedSelectIndexes.contains(i)) {
                            entity.setValue(key, null);
                        } else {
                            entity.setValue(key, row[i]);
                        }
                    }
                }
            } else if (!keys.isEmpty()) {
                if (!notPermittedSelectIndexes.isEmpty()) {
                    entity.setValue(keys.get(0), null);
                } else {
                    entity.setValue(keys.get(0), item);
                }
            }
        }

        tx.commit();
    }

    return entities;
}

From source file:gr.upatras.ece.nam.baker.impl.BakerJpaController.java

@SuppressWarnings("unchecked")
public List<BunMetadata> readBunsMetadata(Long categoryid, int firstResult, int maxResults) {
    EntityManager entityManager = entityManagerFactory.createEntityManager();
    //Query q = entityManager.createQuery("SELECT m FROM BunMetadata m");
    Query q;

    if ((categoryid != null) && (categoryid >= 0))
        q = entityManager.createQuery(//from   www.  j  a va 2 s . c  o m
                "SELECT a FROM BunMetadata a WHERE a.categories.id=" + categoryid + " ORDER BY a.id");
    else
        q = entityManager.createQuery("SELECT a FROM BunMetadata a ORDER BY a.id");

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

From source file:gr.upatras.ece.nam.baker.impl.BakerJpaController.java

@SuppressWarnings("unchecked")
public List<ApplicationMetadata> readAppsMetadataForOwnerID(Long ownerid, int firstResult, int maxResults) {
    EntityManager entityManager = entityManagerFactory.createEntityManager();
    //Query q = entityManager.createQuery("SELECT m FROM BunMetadata m");
    Query q;

    if ((ownerid != null) && (ownerid >= 0))
        q = entityManager.createQuery(/*from www . j  av  a 2  s  .  c  o m*/
                "SELECT a FROM ApplicationMetadata a WHERE a.owner.id=" + ownerid + " ORDER BY a.id");
    else
        q = entityManager.createQuery("SELECT a FROM ApplicationMetadata a ORDER BY a.id");

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

From source file:gr.upatras.ece.nam.baker.impl.BakerJpaController.java

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

    if ((categoryid != null) && (categoryid >= 0))
        q = entityManager.createQuery(// w  w w. j ava2s. co  m
                "SELECT a FROM ApplicationMetadata a WHERE a.categories.id=" + categoryid + " ORDER BY a.id");
    else
        q = entityManager.createQuery("SELECT a FROM ApplicationMetadata a ORDER BY a.id");
    q.setFirstResult(firstResult);
    q.setMaxResults(maxResults);
    return q.getResultList();
}

From source file:corner.orm.gae.impl.PaginatedJapEntityService.java

License:asdf

/**
* 
* magic paginate method./* w  w w . ja  v a2  s . c o m*/
* eg:
* <code>
*  options.setPage(2);
*
*
*  paginate(Member.class,new Object[]{"email=?","asdf@asdf.net"},"userName desc",options)
        
*  paginate(Member.class,"email='asdf@asdf.net'","userName desc",options)
*
*  List conditions = new ArrayList();
*  conditions.add("userName=? and password=?");
*  conditions.add(userName);
*  conditions.add(password);
*  paginate(Member.class,conditions,"userName desc",options)
* 
* </code>
* Magic conditions query criteria
* @param persistClass persistence class
* @param conditions query criteria
* @param order order by sql
* @param options pagination options.
* @return include result and totalRecord.
*/
public PaginationList paginate(final Class<?> persistClass, final Object conditions, final String order,
        final PaginationOptions options) {
    final Iterable con = typeCoercer.coerce(conditions, Iterable.class);

    return (PaginationList) this.template.execute(new JpaCallback() {
        @Override
        public Object doInJpa(EntityManager entityManager) throws PersistenceException {

            final Iterator it = con == null ? null : con.iterator();

            String conditionJPQL = buildConditionJPQL(persistClass, it).toString();

            //query list
            final StringBuffer queryJPQL = new StringBuffer(conditionJPQL);
            appendOrder(queryJPQL, order);
            queryJPQL.insert(0, "select root." + EntityConstants.ID_PROPERTY_NAME);
            Query query = entityManager.createQuery(queryJPQL.toString());

            //count query
            final StringBuffer countJPQL = new StringBuffer(conditionJPQL);
            countJPQL.insert(0, "select count(root) ");
            Query countQuery = entityManager.createQuery(countJPQL.toString());

            if (it != null) {
                int i = 0;
                while (it.hasNext()) {
                    i++;
                    Object obj = it.next();
                    query.setParameter(String.valueOf(i), obj);
                    countQuery.setParameter(String.valueOf(i), obj);
                }
            }
            //get perpage
            int perPage = options.getPerPage();
            int page = options.getPage();
            if (page < 1) {
                page = 1;
            }
            query.setFirstResult((page - 1) * perPage);
            query.setMaxResults(perPage);
            PaginationList list = new PaginationList(query.getResultList().iterator(), options);

            //query total record number
            //beacause jpa rowCount is integer type.so convert as long
            options.setTotalRecord(Long.parseLong(countQuery.getSingleResult().toString()));
            return list;
        }
    });
}

From source file:org.opentides.dao.impl.BaseEntityDaoJpaImpl.java

/**
 * {@inheritDoc}/*w w w .  j  ava2  s. c  om*/
 */
@Override
@SuppressWarnings("unchecked")
public final List<T> findByNamedQuery(final String name, final Map<String, Object> params, int start,
        int total) {
    String queryString = getJpqlQuery(name);
    Query queryObject = getEntityManager().createQuery(queryString);
    if (params != null) {
        for (Map.Entry<String, Object> entry : params.entrySet()) {
            if (entry.getKey() != null && entry.getKey().startsWith("hint.")) {
                queryObject.setHint(entry.getKey().substring(5), entry.getValue());
            } else {
                queryObject.setParameter(entry.getKey(), entry.getValue());
            }
        }
    }
    if (start > -1)
        queryObject.setFirstResult(start);
    if (total > -1)
        queryObject.setMaxResults(total);
    return queryObject.getResultList();
}

From source file:gov.utah.dts.det.ccl.dao.impl.FacilityDaoImpl.java

@Override
public List<FacilitySearchView> searchFacilities(FacilitySearchCriteria criteria, SortBy sortBy, int page,
        int resultsPerPage) {
    StringBuilder sb = new StringBuilder(FACILITY_SEARCH_QUERY);
    buildSearchQueryString(sb, criteria, sortBy);

    Query query = buildSearchQuery(sb.toString(), criteria);

    int maxResults = resultsPerPage == 0 ? 250 : resultsPerPage;
    int firstResult = page * resultsPerPage;
    query.setFirstResult(firstResult);
    query.setMaxResults(maxResults);// w  w w  .j a v  a 2 s . c  om

    List<FacilitySearchView> facilities = query.getResultList();
    for (FacilitySearchView f : facilities) {
        f.getLicenses().size();
    }

    return facilities;
}

From source file:org.medici.bia.dao.usermessage.UserMessageDAOJpaImpl.java

/**
 * //from ww w.  j  a v  a  2 s . c  o  m
 */
public Page searchMYSQL(UserMessageSearch userMessageSearch, PaginationFilter paginationFilter)
        throws PersistenceException {
    // We prepare object of return method.
    Page page = new Page(paginationFilter);

    Query query = null;
    // We set size of result.
    if (paginationFilter.getTotal() == null) {
        String countQuery = "SELECT COUNT(*) " + userMessageSearch.toJPAQuery();

        query = getEntityManager().createQuery(countQuery);
        page.setTotal(new Long((Long) query.getSingleResult()));
        page.setTotalPages(PageUtils.calculeTotalPages(page.getTotal(), page.getElementsForPage()));
    }

    String objectsQuery = userMessageSearch.toJPAQuery();
    paginationFilter = generatePaginationFilterMYSQL(userMessageSearch, paginationFilter);

    String jpql = objectsQuery + getOrderByQuery(paginationFilter.getSortingCriterias());
    logger.info("JPQL Query : " + jpql);
    query = getEntityManager().createQuery(jpql);
    // We set pagination  
    query.setFirstResult(PageUtils.calculeStart(page.getThisPage(), page.getElementsForPage()));
    query.setMaxResults(page.getElementsForPage());

    // We manage sorting (this manages sorting on multiple fields)

    // We set search result on return method
    page.setList(query.getResultList());

    return page;
}