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.fracturedatlas.athena.apa.impl.jpa.JpaApaAdapter.java

private Set<JpaRecord> getRecordsByType(AthenaSearch athenaSearch, EntityManager em) {
    Set<JpaRecord> finishedTicketsSet = null;

    Query query = em.createQuery("from JpaRecord as ticket where type=:ticketType").setParameter("ticketType",
            athenaSearch.getType());/*from   w w w  .j  av a  2  s .  c o m*/

    if (athenaSearch.getLimit() != null) {
        query.setMaxResults(athenaSearch.getLimit());
    }

    if (athenaSearch.getStart() != null) {
        query.setFirstResult(athenaSearch.getStart());
    }

    finishedTicketsSet = new HashSet<JpaRecord>(query.getResultList());
    return finishedTicketsSet;
}

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

public List<Document> listTopDocuments(Long userId, Date startDate, Date endDate, int count) {
    final StopWatch stopWatch = new StopWatch();
    stopWatch.start();//from www  .  ja  v a 2 s . c o m

    final Query query = this.em
            .createQuery("select d from Topic topic join topic.topicDocuments td join td.document d "
                    + "   where topic.userId = :userId "
                    + "     and td.creationDate > :startDate and td.creationDate < :endDate "
                    + "     and td.score > 0.2                                            "
                    + "     order by td.score desc");
    query.setParameter("userId", userId);
    query.setParameter("startDate", startDate);
    query.setParameter("endDate", endDate);
    query.setFirstResult(0);
    query.setMaxResults(count);

    query.setLockMode(LockModeType.NONE);

    @SuppressWarnings("unchecked")
    final List<Document> range = query.getResultList();

    stopWatch.stop();
    logger.debug(stopWatch.toString());

    return range;
}

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

@SuppressWarnings("unchecked")
public List<ImportantTerm> getImportantTerms(Long documentId, int howMany, boolean filterStopWords) {

    final Query query;

    if (filterStopWords) {
        query = this.em.createQuery("select dt from DocumentTerm dt join dt.document d join dt.term t "
                + " where d.id = :documentId and t.valueLowercase NOT IN (:stopWords) "
                + "   and dt.tfIdf is not null order by dt.tfIdf DESC");
        query.setParameter("stopWords", StopWords.ENGLISH);
    } else {//from w w w .j av  a 2  s  .co m
        query = this.em.createQuery("select dt from DocumentTerm dt join dt.document d join dt.term t "
                + " where d.id = :documentId and dt.tfIdf is not null order by dt.tfIdf DESC");
    }
    query.setParameter("documentId", documentId);
    query.setMaxResults(howMany);

    final List<DocumentTerm> documentTerms = query.getResultList();

    float maxTfIdf = -1.0f;

    for (final DocumentTerm documentTerm : documentTerms) {
        if (documentTerm.getTfIdf() > maxTfIdf) {
            maxTfIdf = documentTerm.getTfIdf();
        }
    }

    final List<ImportantTerm> importantTerms = new ArrayList<ImportantTerm>(documentTerms.size());

    for (final DocumentTerm documentTerm : documentTerms) {
        importantTerms.add(new ImportantTerm(documentTerm.getTerm().getValueLowercase(),
                documentTerm.getCount(), documentTerm.getTfIdf(), maxTfIdf));
    }

    return importantTerms;
}

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

/**
 * {@inheritDoc}/* ww  w.j  a  va2s .c  o  m*/
 */
@Override
public Page searchVolumesByDigitization(Integer volNum, Integer volNumBetween,
        PaginationFilter paginationFilter) throws PersistenceException {
    Page page = new Page(paginationFilter);

    Query query = null;
    //String toSearch = new String("FROM People WHERE personId IN (SELECT DISTINCT person.personId FROM org.medici.bia.domain.PoLink WHERE titleOccList.titleOccId=" + titleOccToSearch + ")");
    //MD: The next query is builded for test if is possible order result by date of Title Occupation
    String toSearch = new String("FROM Volume WHERE volNum >= " + volNum + " AND volNum <= " + volNumBetween
            + " AND logicalDelete = false");

    if (paginationFilter.getTotal() == null) {
        String countQuery = "SELECT COUNT(*) " + toSearch;
        query = getEntityManager().createQuery(countQuery);
        page.setTotal(new Long((Long) query.getSingleResult()));
    }

    //MD: We have a pagination filter already parameterized
    //paginationFilter = generatePaginationFilterMYSQL(paginationFilter);

    query = getEntityManager().createQuery(toSearch + getOrderByQuery(paginationFilter.getSortingCriterias()));

    query.setFirstResult(paginationFilter.getFirstRecord());
    query.setMaxResults(paginationFilter.getLength());

    page.setList(query.getResultList());

    return page;
}

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

/**
 * This search method can also be used for distributed search because it uses the common interface types of the
 * ServiceAPI//from w  w w.j  a  v  a 2  s  .  c  o m
 * 
 * @param <E>
 *            interface name of &quot;type&quot; of objects to return, i.e. IProcessListVO, IFlowListVo, ...
 * @param dataSetClassType
 *            Class object of T, i.e. IProcessListVO.class
 * @param params
 *            search parameter as ParameterTool object
 * @param startPosition
 *            start index for first search result
 * @param pageSize
 *            size of one page of search results
 * @param sortCriterium
 *            field name of object which is used for ordering
 * @param sortOrder
 *            define the ordering of the result
 * @param mostRecentVersionOnly
 *            flag to indicate if only the most recent version of a data set shall be returned if multiple versions
 *            exist
 * @param stocks
 *            stocks
 * @return list of objects of the given interface E
 */
public <E extends IDataSetListVO> List<E> searchDist(Class<E> dataSetClassType, ValueParser params,
        int startPosition, int pageSize, String sortCriterium, SortOrder sortOrder,
        boolean mostRecentVersionOnly, IDataStockMetaData[] stocks, IDataStockMetaData excludeStock,
        DistributedSearchLog log) {

    // avoid a lot of null checks
    if (params == null) {
        params = new ValueParser();
    }
    LOGGER.trace("searching for {}", dataSetClassType.getName());

    Query query = this.createQueryObject(params, sortCriterium, sortOrder, false, mostRecentVersionOnly, stocks,
            excludeStock);

    if (startPosition > 0) {
        query.setFirstResult(startPosition);
    }
    if (pageSize > 0) {
        query.setMaxResults(pageSize);
    }

    List<E> dataSets = query.getResultList();

    if (LOGGER.isTraceEnabled()) {
        for (IDataSetListVO ds : dataSets) {
            LOGGER.trace("name: {}, defaultname: {}", ds.getName().getValue(), ds.getDefaultName());
        }
    }

    // OK, search also in other systems
    if (params.exists("distributed") && params.getBoolean("distributed")) {
        LOGGER.info("initiating distributed search");
        ForeignDataSetsHelper foreignHelper = new ForeignDataSetsHelper();
        List<E> foreignProcesses = foreignHelper.foreignSearch(dataSetClassType, params, log);
        if (foreignProcesses != null) {
            LOGGER.debug("returning {} results from foreign nodes", foreignProcesses.size());
        }
        dataSets.addAll(foreignProcesses);
    }
    return dataSets;
}

From source file:com.lhfs.fsn.dao.testReport.impl.TestReportDaoImpl.java

/**
 * /*  w ww .  j  a  v a 2  s.  co  m*/
 * @author longxianzhen 20150807
 */
@SuppressWarnings("unchecked")
@Override
public List<TestResult> getReportsOfDealerAllPassWithPage(String config, int page, int pageSize)
        throws DaoException {
    try {
        String sql = " SELECT tr.id,tr.service_order,tr.publish_flag,tr.last_modify_time,"
                + "ip.batch_serial_no,ip.production_date,p.`name` ,tr.last_modify_user,"
                + "tr.back_result,tr.back_time,p.barcode FROM test_result tr "
                + "LEFT JOIN product_instance ip ON ip.id=tr.sample_id "
                + "LEFT JOIN product p ON p.id=ip.product_id ";
        sql += config;
        Query query = entityManager.createNativeQuery(sql);
        query.setFirstResult((page - 1) * pageSize);
        query.setMaxResults(pageSize);
        List<Object[]> objs = query.getResultList();
        List<TestResult> trs = new ArrayList<TestResult>();
        if (objs != null && objs.size() > 0) {
            for (Object[] obj : objs) {
                TestResult tr = new TestResult();
                tr.setId(obj[0] != null ? Long.parseLong(obj[0].toString()) : -1L);
                tr.setServiceOrder(obj[1] != null ? obj[1].toString() : "");
                tr.setPublishFlag((Character) obj[2]);
                tr.setLastModifyTime(obj[3] == null ? null : (Date) obj[3]);
                ProductInstance pi = new ProductInstance();
                pi.setBatchSerialNo(obj[4] != null ? obj[4].toString() : "");
                pi.setProductionDate(obj[5] == null ? null : (Date) obj[5]);
                Product pro = new Product();
                pro.setName(obj[6] != null ? obj[6].toString() : "");
                pro.setPackageFlag('0');
                pro.setBarcode(obj[10] != null ? obj[10].toString() : "");
                pi.setProduct(pro);
                pi.getProduct().setPackageFlag('0');
                tr.setSample(pi);
                tr.setLastModifyUserName(obj[7] != null ? obj[7].toString() : "");
                tr.setBackResult(obj[8] != null ? obj[8].toString() : "");
                tr.setBackTime(obj[9] == null ? null : (Date) obj[9]);
                trs.add(tr);
            }
        }
        return trs;
    } catch (Exception e) {
        e.printStackTrace();
        throw new DaoException("TestReportDaoImpl.getReportsOfDealerAllPassWithPage()-->" + e.getMessage(), e);
    }
}

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

public List getMostCommentedWeblogs(Date startDate, Date endDate, int offset, int length)
        throws WebloggerException {

    Query query = null;

    if (endDate == null)
        endDate = new Date();

    if (startDate != null) {
        Timestamp start = new Timestamp(startDate.getTime());
        Timestamp end = new Timestamp(endDate.getTime());
        query = strategy.getNamedQuery("WeblogEntryComment.getMostCommentedWebsiteByEndDate&StartDate");
        query.setParameter(1, end);//from  www.j av a  2  s .  c o m
        query.setParameter(2, start);
    } else {
        Timestamp end = new Timestamp(endDate.getTime());
        query = strategy.getNamedQuery("WeblogEntryComment.getMostCommentedWebsiteByEndDate");
        query.setParameter(1, end);
    }
    if (offset != 0) {
        query.setFirstResult(offset);
    }
    if (length != -1) {
        query.setMaxResults(length);
    }
    List queryResults = query.getResultList();
    List results = new ArrayList();
    for (Iterator iter = queryResults.iterator(); iter.hasNext();) {
        Object[] row = (Object[]) iter.next();
        StatCount sc = new StatCount((String) row[1], // website id
                (String) row[2], // website handle
                (String) row[3], // website name
                "statCount.weblogCommentCountType", // stat type
                ((Long) row[0]).longValue()); // # comments
        sc.setWeblogHandle((String) row[2]);
        results.add(sc);
    }
    // Original query ordered by desc # comments.
    // JPA QL doesn't allow queries to be ordered by agregates; do it in memory
    Collections.sort(results, statCountCountReverseComparator);

    return results;
}

From source file:com.lhfs.fsn.dao.testReport.impl.TestReportDaoImpl.java

/**
 * ??/*from w ww . j a v  a 2s. c o m*/
 * @param businessUnit
 * @param page
 * @param pageSize
 * @return
 */
public List<ProductJGVO> getProductByProducerBusinessUnit(BusinessUnit businessUnit, int page, int pageSize) {
    String sql = "select  p.id,p.name,p.format,p.status,p.product_type,"
            + "(SELECT pci.name FROM product_category_info pci WHERE pci.id = p.category_id) categoryName ";
    sql += " FROM product p where p.producer_id=?1";
    Query query = entityManager.createNativeQuery(sql);
    query.setParameter(1, businessUnit.getId());
    query.setFirstResult((page - 1) * pageSize);
    query.setMaxResults(pageSize);
    query.getResultList();
    List<Object[]> objs = query.getResultList();
    List<ProductJGVO> proList = new ArrayList<ProductJGVO>();
    for (Object[] obj : objs) {
        ProductJGVO e = new ProductJGVO();
        e.setId(obj[0] == null ? null : Long.parseLong(obj[0].toString()));
        e.setProName(obj[1] == null ? null : obj[1].toString());
        e.setFormat(obj[2] == null ? null : obj[2].toString());
        e.setStatus(obj[3] == null ? null : obj[3].toString());
        e.setProductType(obj[4] == null ? null : Integer.parseInt(obj[4].toString()) == 2 ? "" : "?");
        e.setCategoryName(obj[5] == null ? null : obj[5].toString());
        proList.add(e);
    }
    return proList;
}

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

/**
 * This method (local lsearch) works as lsearch method for datasets only on local database entities, i.e. Process,
 * Flow, ... To use a lsearch method which
 * also works distributed use the corresponding lsearch method
 * //w  ww.j a  v  a 2  s .  c  o m
 * @param <T>
 *            Class name of &quot;type&quot; of objects to return, i.e. Process, Flow, ...
 * @param params
 *            lsearch parameters as key-value pairs
 * @param startPosition
 *            start index within the whole list of lsearch results
 * @param pageSize
 *            pages size, i.e. maximum count of results to return
 * @param sortCriterium
 *            name of the objects field which should be used for sorting
 * @param ascending
 *            define ordering of result
 * @param mostRecentVersionOnly
 *            flag to indicate if only the most recent version of a data set shall be returned if multiple versions
 *            exist
 * @param stocks
 *            stocks
 * @param excludeStock
 *            stock that shall be excluded from the search (may be <code>null</code>)
 * @return list of datasets of type T matching the lsearch criteria
 */
@SuppressWarnings("unchecked")
public List<T> lsearch(ValueParser params, int startPosition, int pageSize, String sortCriterium,
        boolean ascending, boolean mostRecentVersionOnly, IDataStockMetaData[] stocks,
        IDataStockMetaData excludeStock) {
    List<T> dataSets = null;

    Query query = this.createQueryObject(params, sortCriterium,
            ascending ? SortOrder.ASCENDING : SortOrder.DESCENDING, false, mostRecentVersionOnly, stocks,
            excludeStock);

    if (startPosition > 0) {
        query.setFirstResult(startPosition);
    }
    if (pageSize > 0) {
        query.setMaxResults(pageSize);
    }

    dataSets = query.getResultList();

    return dataSets;
}

From source file:com.sun.socialsite.userapi.UserManagerImpl.java

public List<User> getUsersStartingWith(String startsWith, Boolean enabled, int offset, int length)
        throws UserManagementException {
    List<User> users = new ArrayList<User>();
    Query query = null;
    if (enabled != null) {
        if (startsWith != null) {
            query = getNamedQuery("User.findByUserIdOrEmailAddressPattern&Enabled");
            query.setParameter("enabled", enabled);
            query.setParameter("pattern", startsWith + '%');
        } else {//from w  w  w . jav  a 2 s.  co m
            query = getNamedQuery("User.findByEnabled");
            query.setParameter("enabled", enabled);
        }
    } else {
        if (startsWith != null) {
            query = getNamedQuery("User.findByUserIdOrEmailAddressPattern");
            query.setParameter("pattern", startsWith + '%');
        } else {
            query = getNamedQuery("User.getAll");
        }
    }

    if (offset != 0) {
        query.setFirstResult(offset);
    }
    if (length != -1) {
        query.setMaxResults(length);
    }
    List results = query.getResultList();
    if (results != null) {
        for (Object obj : results) {
            users.add((User) obj);
        }
    }
    return users;
}