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:com.jaspersoft.ireport.designer.data.fieldsproviders.ejbql.EJBQLFieldsReader.java

@SuppressWarnings("unchecked")
public Vector readFields() throws Exception {
    prepareQuery();/*from w  w  w .  j a  va2 s. c o m*/

    Vector fields = new Vector();
    EntityManager em = null;
    Query query = null;
    setSingleClassName(null);
    try {

        IReportConnection conn = IReportManager.getInstance().getDefaultConnection();
        if (!(conn instanceof EJBQLConnection)) {
            throw new Exception("No EJBQL connection selected.");
        }

        em = ((EJBQLConnection) conn).getEntityManager();

        query = em.createQuery(queryString);

        for (Iterator iter = queryParameters.keySet().iterator(); iter.hasNext();) {
            String parameterName = (String) iter.next();
            query.setParameter(parameterName, queryParameters.get(parameterName));
        }

        query.setMaxResults(1);
        List list = query.getResultList();

        if (list.size() > 0) {
            Object obj = list.get(0);

            if (obj != null && obj.getClass().isArray()) {
                // Fields array...
                Object[] fiels_obj = (Object[]) obj;
                for (int i = 0; i < fiels_obj.length; ++i) {
                    fields.add(createField(fiels_obj[i], i));
                }
            } else {
                setSingleClassName(obj.getClass().getName());
                fields = getFields(obj);
            }
        }

        return fields;

    } catch (Exception ex) {
        ex.printStackTrace();
        throw ex;
    } finally {

    }
}

From source file:com.sun.socialsite.business.impl.JPAAppManagerImpl.java

/**
 * Note: using SuppressWarnings annotation because the JPA API is not genericized.
 *//*from   w w w .  j  a  v a2 s .  c  o  m*/
@SuppressWarnings(value = "unchecked")
public List<App> getApps(int offset, int length) throws SocialSiteException {
    Query query = strategy.getNamedQuery("App.getAll");
    if (offset != 0) {
        query.setFirstResult(offset);
    }
    if (length != -1) {
        query.setMaxResults(length);
    }
    return (List<App>) query.getResultList();
}

From source file:com.htm.db.DatabaseAccessProviderJPA.java

public List<IWorkItem> query(String whereClause, int maxResults) throws DatabaseException {

    String queryString = "SELECT * FROM Workitemtaskview wiview ";

    /* If a where clause was specified attach it to the query */
    if (!StringUtils.isEmpty(whereClause)) {
        queryString += "where " + whereClause;
    }//from   w  w w .j  av  a  2  s.c o  m
    log.debug("Query Workitemtaskview - SQL Query : " + queryString);

    /* Execute a query where Workitemtaskview objects are expected to be returned */
    Query query = em.createNativeQuery(queryString, Workitemtaskview.class);
    if (maxResults > 0) {
        query.setMaxResults(maxResults);
    }

    List<?> workItemEntities = executeMultipleResultQuery(query);

    /* List that is to be returned. It contains work item models */
    List<IWorkItem> workItems = new ArrayList<IWorkItem>();

    if (workItemEntities != null) {
        /* Create a work item from each work item view entity */
        Iterator<?> iter = workItemEntities.iterator();
        while (iter.hasNext()) {
            Workitemtaskview viewEntity = (Workitemtaskview) iter.next();
            /*
             * Get the underlying work item of the view entity
             */
            IWorkItem workItem = getWorkItem(Integer.toString(viewEntity.getWiid()));
            workItems.add(workItem);
        }
    }
    return workItems;
}

From source file:com.sun.socialsite.business.impl.JPAAppManagerImpl.java

/**
 * Note: using SuppressWarnings annotation because the JPA API is not genericized.
 *//* www .ja  v a  2 s  .  c  o m*/
@SuppressWarnings(value = "unchecked")
public List<App> getOldestApps(int offset, int length) throws SocialSiteException {
    Query query = strategy.getNamedQuery("App.getOldest");
    if (offset != 0) {
        query.setFirstResult(offset);
    }
    if (length != -1) {
        query.setMaxResults(length);
    }
    return (List<App>) query.getResultList();
}

From source file:com.sun.socialsite.business.impl.JPAAppManagerImpl.java

/**
 * Note: using SuppressWarnings annotation because the JPA API is not genericized.
 *//*w w  w. ja  v a  2s .  c  om*/
@SuppressWarnings(value = "unchecked")
public List<App> getAppsInDirectory(int offset, int length) throws SocialSiteException {
    Query query = strategy.getNamedQuery("App.getAllInDirectory");
    if (offset != 0) {
        query.setFirstResult(offset);
    }
    if (length != -1) {
        query.setMaxResults(length);
    }
    return (List<App>) query.getResultList();
}

From source file:br.org.indt.ndg.server.result.ResultHandlerBean.java

@Override
public QueryInputOutputVO getResultListDB(String surveyId, QueryInputOutputVO queryIOVO)
        throws MSMApplicationException, MSMSystemException {
    if (queryIOVO == null) {
        queryIOVO = new QueryInputOutputVO();
    }/*  w  w  w  . j av a 2  s. c  om*/

    MSMBusinessDelegate bd = new MSMBusinessDelegate();

    String sqlCommand = "SELECT U FROM Result U WHERE survey.idSurvey = " + surveyId;

    if ((queryIOVO.getFilterText() != null) && (queryIOVO.getFilterFields() != null)) {
        sqlCommand += SqlUtil.getFilterCondition(queryIOVO.getFilterText(), queryIOVO.getFilterFields());
    }

    if ((queryIOVO.getSortField() != null) && (queryIOVO.getIsDescending() != null)) {
        sqlCommand += SqlUtil.getSortCondition(queryIOVO.getSortField(), queryIOVO.getIsDescending());
    }

    Query q = manager.createQuery(sqlCommand);
    queryIOVO.setRecordCount(q.getResultList().size());

    if ((queryIOVO.getPageNumber() != null) && (queryIOVO.getRecordsPerPage() != null)) {
        q.setFirstResult((queryIOVO.getPageNumber() - 1) * queryIOVO.getRecordsPerPage());
        q.setMaxResults(queryIOVO.getRecordsPerPage());
    }

    ArrayList<Object> resultList = new ArrayList<Object>();
    ArrayList<Result> resultsListDB = (ArrayList<Result>) q.getResultList();
    ArrayList<ResultVO> notNullResults = new ArrayList<ResultVO>();

    for (Result result : resultsListDB) {
        Collection<TransactionLogVO> logs = bd.getResultReceived(surveyId, result.getIdResult());
        HashMap<String, TransactionLogVO> map = new HashMap<String, TransactionLogVO>();

        for (TransactionLogVO rlog : logs) {
            map.put(rlog.getResultId(), rlog);
        }

        ResultVO bean = new ResultVO();

        try {
            Result currentResult = manager.find(Result.class, result.getIdResult());

            bean.setIdResult(currentResult.getIdResult());
            bean.setSurveyId(currentResult.getSurvey().getIdSurvey());
            bean.setImei(currentResult.getImei().getImei());

            if ((currentResult.getTitle() == null) || (currentResult.getLatitude() == null)
                    || (currentResult.getLongitude() == null)) {
                ResultParser parser = new ResultParser();
                ResultXml resultXML = parser.parseResult(new StringBuffer(result.getResultXml()), "UTF-8");

                bean.setTitle(resultXML.getTitle());
                bean.setLat(resultXML.getLatitude());
                bean.setLon(resultXML.getLongitude());

                currentResult.setTitle(resultXML.getTitle());
                currentResult.setLatitude(resultXML.getLatitude());
                currentResult.setLongitude(resultXML.getLongitude());

                manager.merge(currentResult);
            } else {
                bean.setTitle(currentResult.getTitle());
                bean.setLat(currentResult.getLatitude());
                bean.setLon(currentResult.getLongitude());
            }

            if (!logs.isEmpty()) {
                TransactionLogVO t = map.get(result.getIdResult());

                if (t != null) {
                    bean.setDate(SystemUtils.toDate(t.getDtLog()));
                    bean.setUser(t.getUser());
                }
            }

            // order results by title - ascending
            if (bean.getTitle() == null) {
                resultList.add(bean);
            } else {
                if (notNullResults.size() == 0) {
                    notNullResults.add(bean);
                } else {
                    if (bean.getTitle().compareToIgnoreCase(
                            notNullResults.get(notNullResults.size() - 1).getTitle()) > 0) {
                        notNullResults.add(bean);
                    } else {
                        notNullResults.add(notNullResults.size() - 1, bean);
                    }
                }
            }
        } catch (Exception e) {
            throw new ResultNotParsedException();
        }
    }

    // results without title come first
    resultList.addAll(notNullResults);

    queryIOVO.setQueryResult(resultList);

    return queryIOVO;
}

From source file:de.micromata.genome.db.jpa.logging.BaseJpaLoggingImpl.java

/**
 * {@inheritDoc}//w  w  w.  j a v a  2 s  . co m
 *
 */

@Override
protected void selectLogsImpl(Timestamp start, Timestamp end, Integer loglevel, String category, String msg,
        List<Pair<String, String>> logAttributes, final int startRow, final int maxRow, List<OrderBy> orderBy,
        final boolean masterOnly, final LogEntryCallback callback) throws EndOfSearch {

    final StopWatch sw = new StopWatch();
    sw.start();

    final StringBuilder queryStringBuilder = new StringBuilder(
            "select lm from " + getMasterClass().getName() + "  as lm");
    if (masterOnly == false) {
        queryStringBuilder.append(" left outer join fetch lm.attributes");
    }

    boolean firstWhere = true;
    // final List<Object> args = new ArrayList<Object>();
    Map<String, Object> argmap = new HashMap<>();
    if (start != null) {
        firstWhere = addWhere(queryStringBuilder, firstWhere, "lm.createdAt >= :createdAtMin");
        argmap.put("createdAtMin", start);
    }
    if (end != null) {
        firstWhere = addWhere(queryStringBuilder, firstWhere, "lm.createdAt <= :createdAtMax");
        argmap.put("createdAtMax", end);
    }
    if (loglevel != null) {
        firstWhere = addWhere(queryStringBuilder, firstWhere, "lm.loglevel >= :logLevelMin");
        argmap.put("logLevelMin", new Short(loglevel.shortValue()));
    }
    if (StringUtils.isNotBlank(category) == true) {
        firstWhere = addWhere(queryStringBuilder, firstWhere, "lm.category = :category");
        argmap.put("category", category);
    }
    if (StringUtils.isNotBlank(msg) == true) {
        firstWhere = addWhere(queryStringBuilder, firstWhere, "lm.shortmessage like :message");
        argmap.put("message", msg + "%");
    }
    if (logAttributes != null) {
        int attrNum = 0;
        for (Pair<String, String> pat : logAttributes) {
            ++attrNum;
            LogAttributeType at = getAttributeTypeByString(pat.getFirst());
            if (at == null) {
                GLog.warn(GenomeLogCategory.Configuration,
                        "SelLogs; Cannot find LogAttribute: " + pat.getFirst());
                continue;
            }
            if (at.isSearchKey() == false) {
                GLog.warn(GenomeLogCategory.Configuration,
                        "SelLogs; LogAttribute not searchable: " + pat.getFirst());
                continue;
            }
            if (StringUtils.contains(pat.getSecond(), "%") == false) {
                firstWhere = addWhere(queryStringBuilder, firstWhere, at.columnName(), " = :attr" + attrNum);
            } else {
                firstWhere = addWhere(queryStringBuilder, firstWhere, at.columnName(), " like :attr" + attrNum);
            }

            argmap.put("attr" + attrNum, pat.getSecond());
        }
    }

    if (CollectionUtils.isEmpty(orderBy) == false) {
        queryStringBuilder.append(" order by ");
        boolean first = true;
        for (OrderBy order : orderBy) {
            if (first == true) {
                first = false;
            } else {
                queryStringBuilder.append(", ");
            }
            String propertyName = convertColumnNameToPropertyName(order.getColumn());
            queryStringBuilder.append("lm.").append((propertyName != null) ? propertyName : order.getColumn()); // eventually
            // requires
            // translation
            // to
            // propertynames
            queryStringBuilder.append(order.isDescending() ? " desc" : " asc");
        }
    }

    EmgrFactory<DefaultEmgr> mgrfac = getEmgrFactory();
    mgrfac.runInTrans(new EmgrCallable<Void, DefaultEmgr>() {
        @Override
        public Void call(DefaultEmgr mgr) {

            Query query = mgr.createQuery(queryStringBuilder.toString());
            for (Map.Entry<String, Object> arg : argmap.entrySet()) {
                query.setParameter(arg.getKey(), arg.getValue());
            }
            query.setFirstResult(startRow);
            if (masterOnly == true) {
                query.setMaxResults(maxRow);
            } else {
                query.setMaxResults(maxRow * 10); // pessimistic assumption:
                // 10 attributes per
                // master entry
            }

            List<M> res = query.getResultList();

            for (M lmDo : res) {
                LogEntry le = new LogEntry();
                copyMasterFields(le, lmDo, masterOnly);
                try {
                    callback.onRow(le);
                } catch (EndOfSearch eos) {
                    break;
                }
            }
            return null;
        }
    });
}

From source file:org.eclipse.jubula.client.core.persistence.ProjectPM.java

/**
 * @param guid// w  w  w .ja v  a2  s . c  om
 *            The GUID to search.
 * @return a String representing the highest version number for this project
 *         GUID
 */
public static synchronized String findHighestVersionNumber(String guid) throws JBException {

    EntityManager session = null;
    try {
        session = Persistor.instance().openSession();
        Query query = session.createQuery("select project from ProjectPO project" //$NON-NLS-1$
                + " inner join fetch project.properties where project.guid = :guid " //$NON-NLS-1$
                + "order by project.properties.majorNumber desc, project.properties.minorNumber desc"); //$NON-NLS-1$
        query.setParameter("guid", guid); //$NON-NLS-1$
        query.setMaxResults(1);
        final List projList = query.getResultList();
        if (projList.isEmpty()) {
            return StringConstants.EMPTY;
        }
        IProjectPO project = (IProjectPO) projList.get(0);
        return project.getMajorProjectVersion() + StringConstants.DOT + project.getMinorProjectVersion();
    } catch (PersistenceException e) {
        log.error(Messages.PersistenceLoadFailed, e);
        throw new JBException(e.getMessage(), MessageIDs.E_PERSISTENCE_LOAD_FAILED);
    } finally {
        Persistor.instance().dropSessionWithoutLockRelease(session);
    }
}

From source file:org.apache.syncope.core.persistence.jpa.dao.JPAAnySearchDAO.java

@Override
@SuppressWarnings("unchecked")
protected <T extends Any<?>> List<T> doSearch(final Set<String> adminRealms, final SearchCond cond,
        final int page, final int itemsPerPage, final List<OrderByClause> orderBy, final AnyTypeKind kind) {

    try {//from  ww w .j ava 2 s.  c  o m
        List<Object> parameters = Collections.synchronizedList(new ArrayList<>());

        SearchSupport svs = new SearchSupport(kind);

        Pair<String, Set<String>> filter = getAdminRealmsFilter(adminRealms, svs, parameters);

        // 1. get the query string from the search condition
        StringBuilder queryString = getQuery(buildEffectiveCond(cond, filter.getRight()), parameters, svs);

        // 2. take into account realms and ordering
        OrderBySupport obs = parseOrderBy(kind, svs, orderBy);
        if (queryString.charAt(0) == '(') {
            queryString.insert(0, buildSelect(obs));
            queryString.append(buildWhere(svs, obs));
        } else {
            queryString.insert(0, buildSelect(obs).append('('));
            queryString.append(')').append(buildWhere(svs, obs));
        }
        queryString.append(filter.getLeft()).append(buildOrderBy(obs));

        // 3. prepare the search query
        Query query = entityManager().createNativeQuery(queryString.toString());

        // 4. page starts from 1, while setFirtResult() starts from 0
        query.setFirstResult(itemsPerPage * (page <= 0 ? 0 : page - 1));

        if (itemsPerPage >= 0) {
            query.setMaxResults(itemsPerPage);
        }

        // 5. populate the search query with parameter values
        fillWithParameters(query, parameters);

        // 6. Prepare the result (avoiding duplicates)
        return buildResult(query.getResultList(), kind);
    } catch (Exception e) {
        LOG.error("While searching for {}", kind, e);
    }

    return Collections.emptyList();
}

From source file:org.orcid.persistence.dao.impl.ProfileDaoImpl.java

@SuppressWarnings("unchecked")
@Override//from   w w  w .  j a  v  a 2s .  c o m
public List<String> findOrcidsByIndexingStatus(Collection<IndexingStatus> indexingStatuses, int maxResults,
        Collection<String> orcidsToExclude) {
    StringBuilder builder = new StringBuilder(
            "SELECT p.orcid FROM profile p WHERE p.indexing_status IN :indexingStatus");
    if (!orcidsToExclude.isEmpty()) {
        builder.append(" AND p.orcid NOT IN :orcidsToExclude");
    }
    // Ordering by indexing status will force re-indexing to be lower
    // priority than normal indexing
    builder.append(
            " ORDER BY (p.last_modified > (NOW() - CAST('1' as INTERVAL HOUR))) DESC, indexing_status, p.last_modified");
    Query query = entityManager.createNativeQuery(builder.toString());
    query.setParameter("indexingStatus", IndexingStatus.getNames(indexingStatuses));
    if (!orcidsToExclude.isEmpty()) {
        query.setParameter("orcidsToExclude", orcidsToExclude);
    }
    query.setMaxResults(maxResults);
    return query.getResultList();
}