Example usage for javax.persistence TypedQuery setMaxResults

List of usage examples for javax.persistence TypedQuery setMaxResults

Introduction

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

Prototype

TypedQuery<X> setMaxResults(int maxResult);

Source Link

Document

Set the maximum number of results to retrieve.

Usage

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);
    query.setFirstResult(count * (page - 1));

    return query.getResultList();
}

From source file:com.creditcloud.common.entities.dao.AbstractReadDAO.java

/**
 * list entity by CriteriaInfo//from  w w  w .  j  av  a2  s  . co  m
 *
 * @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:com.zero.dao.impl.BaseDaoImpl.java

protected Page<T> findPage(CriteriaQuery<T> criteriaQuery, Pageable pageable) {
    Assert.notNull(criteriaQuery);/*from w  w  w  .j av a 2s  . 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(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:org.openmeetings.app.data.basic.Configurationmanagement.java

public Configuration getConfByConfigurationId(long user_level, long configuration_id) {
    try {/*  ww w.  j  a  va2s  .  co m*/
        log.debug("getConfByConfigurationId1: user_level " + user_level);
        if (authLevelManagement.checkAdminLevel(user_level)) {
            Configuration configuration = null;
            TypedQuery<Configuration> query = em.createQuery(
                    "select c from Configuration as c where c.configuration_id = :configuration_id",
                    Configuration.class);
            query.setParameter("configuration_id", configuration_id);
            query.setMaxResults(1);
            try {
                configuration = query.getSingleResult();
            } catch (NoResultException e) {
            }
            log.debug("getConfByConfigurationId4: " + configuration);

            if (configuration != null && configuration.getUser_id() != null) {
                configuration.setUsers(usersDao.getUser(configuration.getUser_id()));
            }
            return configuration;
        } else {
            log.error("[getConfByConfigurationId] Permission denied " + user_level);
        }
    } catch (Exception ex2) {
        log.error("[getConfByConfigurationId]: ", ex2);
    }
    return null;
}

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 w  w.  j  av  a  2  s.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:edu.purdue.cybercenter.dm.service.VocabularyService.java

public edu.purdue.cybercenter.dm.domain.Vocabulary findLatestByUuid(UUID uuid) {
    TypedQuery<edu.purdue.cybercenter.dm.domain.Vocabulary> query = DomainObjectHelper
            .createNamedQuery("Vocabulary.findByUuid", edu.purdue.cybercenter.dm.domain.Vocabulary.class);
    query.setParameter("uuid", uuid);
    query.setMaxResults(1);
    edu.purdue.cybercenter.dm.domain.Vocabulary dbVocabulary;
    try {//  ww  w .ja va2 s  .c o m
        dbVocabulary = domainObjectService.executeTypedQueryWithSingleResult(query);
    } catch (EmptyResultDataAccessException ex) {
        dbVocabulary = null;
    }
    return dbVocabulary;
}

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

protected Page<T> findPage(CriteriaQuery<T> criteriaQuery, Pageable pageable) {
    Assert.notNull(criteriaQuery);/*from   w ww.  j a  v  a 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);
}

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  w  w  . j  a  v a 2 s .c o 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:org.jdal.dao.jpa.JpaDao.java

/**
 * {@inheritDoc}/*from   www . 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:ca.uhn.fhir.jpa.dao.BaseHapiFhirSystemDao.java

private int doPerformReindexingPassForResources(final Integer theCount, TransactionTemplate txTemplate) {
    return txTemplate.execute(new TransactionCallback<Integer>() {
        @SuppressWarnings("unchecked")
        @Override/*w ww . j av  a 2s  .c  o m*/
        public Integer doInTransaction(TransactionStatus theStatus) {
            TypedQuery<ResourceTable> q = myEntityManager.createQuery(
                    "SELECT t FROM " + ResourceTable.class.getSimpleName() + " t WHERE t.myIndexStatus IS null",
                    ResourceTable.class);

            int maxResult = 500;
            if (theCount != null) {
                maxResult = Math.min(theCount, 2000);
            }

            q.setMaxResults(maxResult);
            List<ResourceTable> resources = q.getResultList();
            if (resources.isEmpty()) {
                return 0;
            }

            ourLog.info("Indexing {} resources", resources.size());

            int count = 0;
            long start = System.currentTimeMillis();

            for (ResourceTable resourceTable : resources) {
                try {
                    /*
                     * This part is because from HAPI 1.5 - 1.6 we changed the format of forced ID to be "type/id" instead of just "id"
                     */
                    ForcedId forcedId = resourceTable.getForcedId();
                    if (forcedId != null) {
                        if (isBlank(forcedId.getResourceType())) {
                            ourLog.info("Updating resource {} forcedId type to {}", forcedId.getForcedId(),
                                    resourceTable.getResourceType());
                            forcedId.setResourceType(resourceTable.getResourceType());
                            myForcedIdDao.save(forcedId);
                        }
                    }

                    final IBaseResource resource = toResource(resourceTable, false);

                    @SuppressWarnings("rawtypes")
                    final IFhirResourceDao dao = getDao(resource.getClass());

                    dao.reindex(resource, resourceTable);
                } catch (Exception e) {
                    ourLog.error("Failed to index resource {}: {}",
                            new Object[] { resourceTable.getIdDt(), e.toString(), e });
                    throw new ReindexFailureException(resourceTable.getId());
                }
                count++;
            }

            long delay = System.currentTimeMillis() - start;
            long avg = (delay / resources.size());
            ourLog.info("Indexed {} / {} resources in {}ms - Avg {}ms / resource",
                    new Object[] { count, resources.size(), delay, avg });

            return resources.size();
        }
    });
}