Example usage for javax.persistence Query setMaxResults

List of usage examples for javax.persistence Query setMaxResults

Introduction

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

Prototype

Query setMaxResults(int maxResult);

Source Link

Document

Set the maximum number of results to retrieve.

Usage

From source file:org.medici.bia.dao.document.DocumentDAOJpaImpl.java

/**
 * {@inheritDoc}// w w  w. j a v a 2 s.  com
 */
@Override
public Document findLastEntryDocument() throws PersistenceException {
    Query query = getEntityManager()
            .createQuery("FROM Document WHERE logicalDelete = false ORDER BY dateCreated DESC");
    query.setMaxResults(1);

    return (Document) query.getSingleResult();
}

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

/**
 * /*from   w  ww .  j  ava  2s.  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;
}

From source file:org.apache.roller.weblogger.business.jpa.JPAMediaFileManagerImpl.java

/**
 * {@inheritDoc}//  www  .  ja  v  a2 s .co  m
 */
public List<MediaFile> searchMediaFiles(Weblog weblog, MediaFileFilter filter) throws WebloggerException {

    List<Object> params = new ArrayList<Object>();
    int size = 0;
    StringBuilder queryString = new StringBuilder();
    StringBuilder whereClause = new StringBuilder();
    StringBuilder orderBy = new StringBuilder();

    queryString.append("SELECT m FROM MediaFile m WHERE ");

    params.add(size++, weblog);
    whereClause.append("m.directory.weblog = ?").append(size);

    if (!StringUtils.isEmpty(filter.getName())) {
        String nameFilter = filter.getName();
        nameFilter = nameFilter.trim();
        if (!nameFilter.endsWith("%")) {
            nameFilter = nameFilter + "%";
        }
        params.add(size++, nameFilter);
        whereClause.append(" AND m.name like ?").append(size);
    }

    if (filter.getSize() > 0) {
        params.add(size++, filter.getSize());
        whereClause.append(" AND m.length ");
        switch (filter.getSizeFilterType()) {
        case GT:
            whereClause.append(">");
            break;
        case GTE:
            whereClause.append(">=");
            break;
        case EQ:
            whereClause.append("=");
            break;
        case LT:
            whereClause.append("<");
            break;
        case LTE:
            whereClause.append("<=");
            break;
        default:
            whereClause.append("=");
            break;
        }
        whereClause.append(" ?").append(size);
    }

    if (filter.getTags() != null && filter.getTags().size() > 1) {
        whereClause.append(" AND EXISTS (SELECT t FROM MediaFileTag t WHERE t.mediaFile = m and t.name IN (");
        for (String tag : filter.getTags()) {
            params.add(size++, tag);
            whereClause.append("?").append(size).append(",");
        }
        whereClause.deleteCharAt(whereClause.lastIndexOf(","));
        whereClause.append("))");
    } else if (filter.getTags() != null && filter.getTags().size() == 1) {
        params.add(size++, filter.getTags().get(0));
        whereClause.append(" AND EXISTS (SELECT t FROM MediaFileTag t WHERE t.mediaFile = m and t.name = ?")
                .append(size).append(")");
    }

    if (filter.getType() != null) {
        if (filter.getType() == MediaFileType.OTHERS) {
            for (MediaFileType type : MediaFileType.values()) {
                if (type != MediaFileType.OTHERS) {
                    params.add(size++, type.getContentTypePrefix() + "%");
                    whereClause.append(" AND m.contentType not like ?").append(size);
                }
            }
        } else {
            params.add(size++, filter.getType().getContentTypePrefix() + "%");
            whereClause.append(" AND m.contentType like ?").append(size);
        }
    }

    if (filter.getOrder() != null) {
        switch (filter.getOrder()) {
        case NAME:
            orderBy.append(" order by m.name");
            break;
        case DATE_UPLOADED:
            orderBy.append(" order by m.dateUploaded");
            break;
        case TYPE:
            orderBy.append(" order by m.contentType");
            break;
        default:
        }
    } else {
        orderBy.append(" order by m.name");
    }

    Query query = strategy
            .getDynamicQuery(queryString.toString() + whereClause.toString() + orderBy.toString());
    for (int i = 0; i < params.size(); i++) {
        query.setParameter(i + 1, params.get(i));
    }

    if (filter.getStartIndex() >= 0) {
        query.setFirstResult(filter.getStartIndex());
        query.setMaxResults(filter.getLength());
    }
    return query.getResultList();
}

From source file:org.key2gym.business.services.OrdersServiceBean.java

@Override
public void addPurchase(Integer orderId, Integer itemId, Integer discountId, Integer quantity)
        throws BusinessException, ValidationException, SecurityViolationException {

    /*//from  w w w  .  ja v  a 2  s. c  o m
     * Checks the caller's roles.
     */
    if (!callerHasAnyRole(SecurityRoles.JUNIOR_ADMINISTRATOR, SecurityRoles.SENIOR_ADMINISTRATOR,
            SecurityRoles.MANAGER)) {
        throw new SecurityViolationException(getString("Security.Operation.Denied"));
    }

    if (orderId == null) {
        throw new NullPointerException("The orderId is null.");
    }

    if (itemId == null) {
        throw new NullPointerException("The itemId is null."); //NOI18N
    }

    if (quantity == null) {
        throw new NullPointerException("The quantity is null.");
    }

    OrderEntity order;
    Item item;
    Discount discount;

    order = em.find(OrderEntity.class, orderId, LockModeType.OPTIMISTIC);

    if (order == null) {
        throw new ValidationException(getString("Invalid.Order.ID"));
    }

    /*
     * Performs additional roles checks.
     */
    Boolean managerRoleRequired = (order.getAttendance() != null && !order.getAttendance().isOpen())
            || !isToday(order.getDate());

    if (managerRoleRequired && !callerHasRole(SecurityRoles.MANAGER)) {
        throw new SecurityViolationException(getString("Security.Operation.Denied"));
    }

    if (quantity <= 0) {
        throw new ValidationException(getString("Invalid.OrderLine.Quantity"));
    }

    item = em.find(Item.class, itemId);

    if (item == null) {
        throw new ValidationException(getString("Invalid.Item.ID"));
    }

    if (item.getItemSubscription() != null && order.getClient() == null) {
        throw new BusinessException(getString("BusinessRule.Order.Casual.CanNotPurchaseSubscriptions"));
    }

    if (discountId == null) {
        discount = null;
    } else {
        discount = em.find(Discount.class, discountId);

        if (discount == null) {
            throw new ValidationException(getString("Invalid.Discount.ID"));
        }
    }

    /*
     * Frozen items can not be ordered.
     */
    if (item.isFrozen()) {
        throw new ValidationException(getString("BusinessRule.Order.ItemFrozen"));
    }

    /*
     * Checks the item's quantity, if it's countable.
     */
    Integer currentQuantity = item.getQuantity();
    if (currentQuantity != null) {
        /*
         * If the item is not in stock, throws a BusinessException.
         * The item's quantity will be decreased after all checks are performed.
         */
        if (currentQuantity == 0) {
            throw new BusinessException(getString("BusinessRule.Order.ItemNotInStock"));
        }
    }

    /*
     * Business logic specific to orders associated with clients.
     */
    if (order.getClient() != null) {
        Client client = order.getClient();
        client.charge(item, quantity, discount);

        if (item.getItemSubscription() != null) {
            client.activate(item.getItemSubscription());
        }
    }

    /*
     * The change should be here, because we have to change the date after
     * all checks have been performed.
     */
    if (currentQuantity != null) {
        item.setQuantity(currentQuantity - quantity);
    }

    /*
     * Attempts to find an appropriate order line.
     */
    OrderLine orderLine;

    Query query;
    if (discount == null) {
        query = em.createNamedQuery("OrderLine.findByOrderAndItemAndNoDiscount");
    } else {
        query = em.createNamedQuery("OrderLine.findByOrderAndItemAndDiscount").setParameter("discount",
                discount);
    }

    query.setParameter("order", order).setParameter("item", item);

    try {
        orderLine = (OrderLine) query.setMaxResults(1).getSingleResult();
    } catch (NoResultException ex) {
        orderLine = null;
    }

    /*
     * Creates a new order line, if none was found.
     */
    if (orderLine == null) {
        orderLine = new OrderLine();
        orderLine.setItem(item);
        orderLine.setOrder(order);
        orderLine.setQuantity(quantity);
        orderLine.setDiscount(discount);
        em.persist(orderLine);

        List<OrderLine> orderLines = order.getOrderLines();
        if (orderLines == null) {
            orderLines = new LinkedList<>();
            order.setOrderLines(orderLines);
        }
        orderLines.add(orderLine);
    } else {
        orderLine.setQuantity(orderLine.getQuantity() + quantity);
    }
}

From source file:fi.vm.sade.organisaatio.dao.impl.OrganisaatioDAOImpl.java

public List<Organisaatio> findOrganisaatioByNimiLike(String organisaatioNimi, int firstResult, int maxResults) {
    LOG.debug("findOrganisaatioByNimiLike()");
    Query query = getEntityManager().createQuery(
            "SELECT o FROM Organisaatio o WHERE UPPER(o.nimiFi) LIKE :orgnimi OR UPPER(o.nimiSv) LIKE :orgnimi "
                    + "OR UPPER(o.nimiEn) LIKE :orgnimi");
    query.setParameter("orgnimi", "%" + organisaatioNimi.toUpperCase() + "%");
    query.setFirstResult(firstResult);//w  w  w  .  j  av  a 2s  .  c om
    query.setMaxResults((maxResults <= 100) ? maxResults + 1 : 101);
    return query.getResultList();
}

From source file:org.medici.bia.dao.document.DocumentDAOJpaImpl.java

/**
 * {@inheritDoc}//from   ww w . j a v  a  2  s.  c o m
 */
@Override
public Document checkVolumeFolio(Integer summaryId) throws PersistenceException {
    Query query = getEntityManager().createQuery(
            "FROM Document WHERE volume.summaryId=:summaryId AND logicalDelete=false ORDER BY folioNum DESC");
    query.setParameter("summaryId", summaryId);

    query.setMaxResults(1);
    return (Document) query.getSingleResult();
}

From source file:net.sf.gazpachoquest.qbe.NamedQueryUtil.java

public <T> List<T> findByNamedQuery(final SearchParameters sp) {
    if (sp == null || !sp.hasNamedQuery()) {
        throw new IllegalArgumentException("searchParameters must be non null and must have a namedQuery");
    }/* w ww  .  j a v  a 2  s.com*/

    Query query = entityManager.createNamedQuery(sp.getNamedQuery());
    String queryString = getQueryString(query);

    // append order by if needed
    if (queryString != null && sp.hasOrders()) {
        // create the sql restriction clausis
        StringBuilder orderClausis = new StringBuilder("order by ");
        boolean first = true;
        for (OrderBy orderBy : sp.getOrders()) {
            if (!first) {
                orderClausis.append(", ");
            }
            orderClausis.append(orderBy.getColumn());
            orderClausis.append(orderBy.isOrderDesc() ? " desc" : " asc");
            first = false;
        }

        if (logger.isDebugEnabled()) {
            logger.debug("appending: [" + orderClausis.toString() + "] to " + queryString);
        }

        query = recreateQuery(query, queryString + " " + orderClausis.toString());
    }

    // pagination
    if (sp.getFirstResult() >= 0) {
        query.setFirstResult(sp.getFirstResult());
    }
    if (sp.getMaxResults() > 0) {
        query.setMaxResults(sp.getMaxResults());
    }

    // named parameters
    setQueryParameters(query, sp);

    // execute
    @SuppressWarnings("unchecked")
    List<T> result = query.getResultList();

    if (result != null && logger.isDebugEnabled()) {
        logger.debug(sp.getNamedQuery() + " returned a List of size: " + result.size());
    }

    return result;
}

From source file:de.iai.ilcd.model.dao.DataSetDao.java

private List<T> getDatasetsFromNonRootDs(IDataStockMetaData dataStock, int startIndex, int pageSize) {
    final String dsField = this.getDataStockField();
    StringBuilder sb = new StringBuilder("SELECT b FROM DataStock a LEFT JOIN a.").append(dsField)
            .append(" b WHERE a.id=:dsId");

    EntityManager em = PersistenceUtil.getEntityManager();
    Query query = em.createQuery(sb.toString());

    query.setParameter("dsId", dataStock.getId());
    query.setFirstResult(startIndex);/*from   w  w w  . ja v a2  s  .  co m*/
    query.setMaxResults(pageSize);

    return query.getResultList();
}

From source file:de.iai.ilcd.model.dao.DataSetDao.java

private List<T> getDatasetsFromRootDs(IDataStockMetaData dataStock, int startIndex, int pageSize) {
    EntityManager em = PersistenceUtil.getEntityManager();
    Query query = em.createQuery("SELECT a FROM " + this.getJpaName() + " a WHERE a.rootDataStock.id=:dsId");

    query.setParameter("dsId", dataStock.getId());
    query.setFirstResult(startIndex);/*from  www  .j a  v a2 s .  c o m*/
    query.setMaxResults(pageSize);

    return query.getResultList();
}

From source file:com.mothsoft.alexis.dao.DocumentDaoImpl.java

@SuppressWarnings("unchecked")
@Override//from  w  ww  .  j a  v  a  2s. co  m
public List<ImportantNamedEntity> getImportantNamedEntities(Long userId, Date startDate, Date endDate,
        int howMany) {
    final Query query = this.em
            .createQuery("SELECT NEW com.mothsoft.alexis.domain.ImportantNamedEntity(ne.name, sum(ne.count)) "
                    + "FROM DocumentNamedEntity ne JOIN ne.document document JOIN document.documentUsers documentUser "
                    + "WHERE document.creationDate >= :startDate AND document.creationDate <= :endDate AND documentUser.user.id = :userId "
                    + "GROUP BY ne.name ORDER BY sum(ne.count) DESC");
    query.setParameter("startDate", startDate);
    query.setParameter("endDate", endDate);
    query.setParameter("userId", userId);
    query.setMaxResults(howMany);
    return query.getResultList();
}