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:com.easyjf.core.dao.impl.GenericDAOImpl.java

public List query(final String queryStr, final Object[] params, final int begin, final int max) {
    List ret = (List) this.getJpaTemplate().execute(new JpaCallback() {

        public Object doInJpa(EntityManager em) throws PersistenceException {
            Query query = em.createQuery(queryStr);
            int parameterIndex = 1;
            if (params != null && params.length > 0) {
                for (Object obj : params) {
                    query.setParameter(parameterIndex++, obj);
                }/*  ww w.j a v  a  2  s .com*/
            }
            if (begin >= 0 && max > 0) {
                query.setFirstResult(begin);
                query.setMaxResults(max);
            }
            return query.getResultList();
        }
    });
    if (ret != null && ret.size() >= 0) {
        return ret;
    } else {
        return new ArrayList();
    }
}

From source file:com.easyjf.core.dao.impl.GenericDAOImpl.java

public List executeNativeQuery(final String nnq, final Object[] params, final int begin, final int max) {
    List ret = (List) this.getJpaTemplate().execute(new JpaCallback() {

        public Object doInJpa(EntityManager em) throws PersistenceException {
            Query query = em.createNativeQuery(nnq);
            int parameterIndex = 1;
            if (params != null && params.length > 0) {
                for (Object obj : params) {
                    query.setParameter(parameterIndex++, obj);
                }//from w  ww .  j  a va  2  s . c  om
            }
            if (begin >= 0 && max > 0) {
                query.setFirstResult(begin);
                query.setMaxResults(max);
            }
            return query.getResultList();
        }
    });
    if (ret != null && ret.size() >= 0) {
        return ret;
    } else {
        return new ArrayList();
    }
}

From source file:org.openhab.persistence.jpa.internal.JpaPersistenceService.java

@Override
public Iterable<HistoricItem> query(FilterCriteria filter) {
    logger.debug("Querying for historic item: {}", filter.getItemName());

    if (!JpaConfiguration.isInitialized) {
        logger.warn("Trying to create EntityManagerFactory but we don't have configuration yet!");
        return Collections.emptyList();
    }/*w  w w  .  j a  v a 2 s  .  c o  m*/

    String itemName = filter.getItemName();
    Item item = getItemFromRegistry(itemName);

    String sortOrder;
    if (filter.getOrdering() == Ordering.ASCENDING)
        sortOrder = "ASC";
    else
        sortOrder = "DESC";

    boolean hasBeginDate = false;
    boolean hasEndDate = false;
    String queryString = "SELECT n FROM " + JpaPersistentItem.class.getSimpleName()
            + " n WHERE n.realName = :itemName";
    if (filter.getBeginDate() != null) {
        queryString += " AND n.timestamp >= :beginDate";
        hasBeginDate = true;
    }
    if (filter.getEndDate() != null) {
        queryString += " AND n.timestamp <= :endDate";
        hasEndDate = true;
    }
    queryString += " ORDER BY n.timestamp " + sortOrder;

    logger.debug("The query: " + queryString);

    EntityManager em = getEntityManagerFactory().createEntityManager();
    try {
        // In RESOURCE_LOCAL calls to EntityManager require a begin/commit
        em.getTransaction().begin();

        logger.debug("Creating query...");
        Query query = em.createQuery(queryString);
        query.setParameter("itemName", item.getName());
        if (hasBeginDate)
            query.setParameter("beginDate", filter.getBeginDate());
        if (hasEndDate)
            query.setParameter("endDate", filter.getEndDate());

        query.setFirstResult(filter.getPageNumber() * filter.getPageSize());
        query.setMaxResults(filter.getPageSize());
        logger.debug("Creating query...done");

        logger.debug("Retrieving result list...");
        @SuppressWarnings("unchecked")
        List<JpaPersistentItem> result = (List<JpaPersistentItem>) query.getResultList();
        logger.debug("Retrieving result list...done");

        List<HistoricItem> historicList = JpaHistoricItem.fromResultList(result, item);
        if (historicList != null) {
            logger.debug(String.format("Convert to HistoricItem: %d", historicList.size()));
        }

        em.getTransaction().commit();

        return historicList;

    } catch (Exception e) {
        logger.error("Error on querying database!");
        logger.error(e.getMessage(), e);
        em.getTransaction().rollback();

    } finally {
        em.close();
    }

    return Collections.emptyList();
}

From source file:eu.forgestore.ws.impl.FStoreJpaController.java

@SuppressWarnings("unchecked")
public List<FStoreUser> readUsers(int firstResult, int maxResults) {
    EntityManager entityManager = entityManagerFactory.createEntityManager();

    Query q = entityManager.createQuery("SELECT m FROM FStoreUser m");
    q.setFirstResult(firstResult);
    q.setMaxResults(maxResults);/* w w  w .  java2  s.  c o m*/
    return q.getResultList();
}

From source file:com.easyjf.core.dao.impl.GenericDAOImpl.java

public List executeNamedQuery(final String queryName, final Object[] params, final int begin, final int max) {
    List ret = (List) this.getJpaTemplate().execute(new JpaCallback() {

        public Object doInJpa(EntityManager em) throws PersistenceException {
            Query query = em.createNamedQuery(queryName);
            int parameterIndex = 1;
            if (params != null && params.length > 0) {
                for (Object obj : params) {
                    query.setParameter(parameterIndex++, obj);
                }/*w ww  .  ja  v  a2s.com*/
            }
            if (begin >= 0 && max > 0) {
                query.setFirstResult(begin);
                query.setMaxResults(max);
            }
            return query.getResultList();
        }
    });
    if (ret != null && ret.size() >= 0) {
        return ret;
    } else {
        return new ArrayList();
    }
}

From source file:nl.strohalm.cyclos.utils.database.DatabaseQueryHandler.java

/**
 * Applies the result limits to the given query
 */// w w  w.j  av a2s .c o  m
public void applyPageParameters(final PageParameters pageParameters, final Query query) {
    Integer firstResult = pageParameters == null ? null : pageParameters.getFirstResult();
    if (firstResult != null && firstResult >= 0) {
        query.setFirstResult(firstResult);
    }
    Integer maxResults = pageParameters == null ? null : pageParameters.getMaxResults();
    if (maxResults != null && maxResults > 0) {
        query.setMaxResults(maxResults);
    }
}

From source file:io.isoft.system.service.NoticeServiceImpl.java

@Override
public MyFilterResult findNotices(MyFilter filter) {
    try {/*www .j a v a2 s .  c om*/
        FilterBuilder filterBuilder = new FilterBuilder();

        String hql = " from CdNotice e ";
        if (filter.arguments.size() > 0)
            hql += " WHERE " + filterBuilder.buildHql(filter, "e");

        //???count?;
        Query countQuery = entityManager.createQuery("select count(*) " + hql);
        if (filter.sorts.size() == 0)
            hql += " ORDER BY e.noticeNo";
        else {
            //?;
            hql += " ORDER BY ";
            int sortIndex = 0;
            for (MyFilterSort myFilterSort : filter.sorts) {
                hql += String.format("  e.%s %s %s", myFilterSort.sortColumn,
                        myFilterSort.isAscending ? "" : "DESC",
                        (++sortIndex == filter.sorts.size()) ? "" : ",");
            }

        }
        //??
        Query query = entityManager.createQuery(hql);

        //?queryquery?
        for (ObjectParameter parameter : filterBuilder.parameters) {
            query.setParameter(parameter.name, parameter.value);
            countQuery.setParameter(parameter.name, parameter.value);
        }
        Object o = countQuery.getSingleResult();
        int recordCount = Integer.parseInt(o.toString());
        int pageStart = (filter.pageIndex) * filter.pageSize;
        List<CdNotice> results = query.setFirstResult(pageStart).setMaxResults(filter.pageSize).getResultList();

        return new MyFilterResult((ArrayList<CdNotice>) results, recordCount);
    } catch (RuntimeException re) {
        throw re;
    }
}

From source file:org.easyj.orm.jpa.SingleJPAEntityDao.java

/**
 * Binds parameter map to the query.//from   w  w w. j  av a 2  s  .c  o  m
 * 
 * There are two special parameters that is of use:
 * {@link SingleService.PARAM_MAX_RESULTS} used to limit maximum results returned
 * {@link SingleService.PARAM_START_POSITION} used to tell the starting position the result should start
 *
 * @param q query to bind parameters
 * @param params parameter map to bind into the query
 * @return true if all parameters where bound successfully, otherwise false
 */
private boolean setParameters(Query q, Map<String, Object> params) {
    if (q != null && params != null) {
        Integer maxResults = (Integer) params.remove(SingleDao.PARAM_MAX_RESULTS);
        if (maxResults != null && maxResults > 0) {
            q.setMaxResults(maxResults.intValue());
        }

        Integer startPosition = (Integer) params.remove(SingleDao.PARAM_START_POSITION);
        if (startPosition != null && startPosition > -1) {
            q.setFirstResult(startPosition.intValue());
        }

        for (Entry<String, Object> o : params.entrySet()) {
            try {
                q.setParameter(o.getKey().trim(), o.getValue());
            } catch (IllegalArgumentException ex) {
                logger.debug("Illegal Query Parameter", ex);
                return false;
            }
        }
    }
    return true;
}

From source file:com.easyjf.core.dao.impl.GenericDAOImpl.java

public List<T> find(final String queryStr, final Object[] params, final int begin, final int max) {
    List<T> ret = (List<T>) this.getJpaTemplate().execute(new JpaCallback() {
        public Object doInJpa(EntityManager em) throws PersistenceException {

            String clazzName = clazz.getName();
            StringBuffer sb = new StringBuffer("select obj from ");
            sb.append(clazzName).append(" obj").append(" where ").append(queryStr);
            Query query = em.createQuery(sb.toString());
            int parameterIndex = 1;
            if (params != null && params.length > 0) {
                for (Object obj : params) {
                    query.setParameter(parameterIndex++, obj);
                }/* www .j  ava2 s.  c o m*/
            }
            if (begin >= 0 && max > 0) {
                query.setFirstResult(begin);
                query.setMaxResults(max);
            }
            if (begin >= 0 && max > 0) {
                query.setFirstResult(begin);
                query.setMaxResults(max);
            }
            return query.getResultList();
        }
    });
    if (ret != null && ret.size() >= 0) {
        return ret;
    } else {
        return new ArrayList<T>();
    }
}

From source file:org.springframework.integration.jpa.core.DefaultJpaOperations.java

@Override
public List<?> getResultListForNativeQuery(String selectQuery, Class<?> entityClass,
        ParameterSource parameterSource, int firstResult, int maxNumberOfResults) {

    final Query query;

    if (entityClass == null) {
        query = entityManager.createNativeQuery(selectQuery);
    } else {/*from   w  ww. j  av  a  2 s . co m*/
        query = entityManager.createNativeQuery(selectQuery, entityClass);
    }

    setParametersIfRequired(selectQuery, parameterSource, query);

    if (firstResult > 0) {
        query.setFirstResult(firstResult);
    }
    if (maxNumberOfResults > 0) {
        query.setMaxResults(maxNumberOfResults);
    }

    return query.getResultList();
}