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.kuali.rice.krad.data.jpa.JpaQueryTranslator.java

@Override
public void convertQueryFlags(org.kuali.rice.core.api.criteria.QueryByCriteria qbc, Query query) {
    //ojb's is 1 based, our query api is zero based
    //final int startAtIndex = criteria.getStartAtIndex() != null ? criteria.getStartAtIndex() + 1 : 1;
    // XXX: FIXME: had to change this to 0...why was this setting start index to 1?
    // experimentation shows that initial offset of 1 is required for OJB criteria tests to pass
    final int startAtIndex = qbc.getStartAtIndex() != null ? qbc.getStartAtIndex() : 0;
    query.setFirstResult(startAtIndex);/*from  w w  w . java2 s. c  om*/

    if (qbc.getMaxResults() != null) {
        //not subtracting one from MaxResults in order to retrieve
        //one extra row so that the MoreResultsAvailable field can be set
        query.setMaxResults(qbc.getMaxResults());
    }
}

From source file:org.opencastproject.usertracking.impl.UserTrackingServiceImpl.java

public Report getReport(String from, String to, int offset, int limit) throws ParseException {
    Report report = new ReportImpl();
    report.setLimit(limit);//from  w  ww.j av a2s .  c o  m
    report.setOffset(offset);

    Calendar calBegin = new GregorianCalendar();
    Calendar calEnd = new GregorianCalendar();
    SimpleDateFormat complex = new SimpleDateFormat("yyyyMMddhhmm");
    SimpleDateFormat simple = new SimpleDateFormat("yyyyMMdd");

    //Try to parse the from calendar
    try {
        calBegin.setTime(complex.parse(from));
    } catch (ParseException e) {
        calBegin.setTime(simple.parse(from));
    }

    //Try to parse the to calendar
    try {
        calEnd.setTime(complex.parse(to));
    } catch (ParseException e) {
        calEnd.setTime(simple.parse(to));
    }

    EntityManager em = null;
    try {
        em = emf.createEntityManager();
        Query q = em.createNamedQuery("countSessionsGroupByMediapackageByIntervall");
        q.setFirstResult(offset);
        q.setMaxResults(limit);
        q.setParameter("begin", calBegin, TemporalType.TIMESTAMP);
        q.setParameter("end", calEnd, TemporalType.TIMESTAMP);

        @SuppressWarnings("unchecked")
        List<Object[]> result = q.getResultList();
        ReportItem item;

        for (Object[] a : result) {
            item = new ReportItemImpl();
            item.setEpisodeId((String) a[0]);
            item.setViews((Long) a[1]);
            item.setPlayed((Long) a[2]);
            report.add(item);
        }
        return report;
    } finally {
        if (em != null && em.isOpen()) {
            em.close();
        }
    }
}

From source file:org.syncope.core.persistence.dao.impl.UserSearchDAOImpl.java

private List<SyncopeUser> doSearch(final Set<Long> adminRoles, final NodeCond nodeCond, final int page,
        final int itemsPerPage) {

    List<Object> parameters = Collections.synchronizedList(new ArrayList<Object>());

    // 1. get the query string from the search condition
    final StringBuilder queryString = getQuery(nodeCond, parameters);

    // 2. take into account administrative roles
    if (queryString.charAt(0) == '(') {
        queryString.insert(0, "SELECT u.user_id FROM ");
        queryString.append(" u WHERE user_id NOT IN (");
    } else {//from   w  w w  .  j  av a 2 s  .  c o  m
        queryString.insert(0, "SELECT u.user_id FROM (");
        queryString.append(") u WHERE user_id NOT IN (");
    }
    queryString.append(getAdminRolesFilter(adminRoles)).append(")");

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

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

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

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

    LOG.debug("Native query\n{}\nwith parameters\n{}", queryString.toString(), parameters);

    // 5. Prepare the result (avoiding duplicates - set)
    final Set<Number> userIds = new HashSet<Number>();
    final List resultList = query.getResultList();

    //fix for HHH-5902 - bug hibernate
    if (resultList != null) {
        for (Object userId : resultList) {
            if (userId instanceof Object[]) {
                userIds.add((Number) ((Object[]) userId)[0]);
            } else {
                userIds.add((Number) userId);
            }
        }
    }

    final List<SyncopeUser> result = new ArrayList<SyncopeUser>(userIds.size());

    SyncopeUser user;
    for (Object userId : userIds) {
        user = userDAO.find(((Number) userId).longValue());
        if (user == null) {
            LOG.error("Could not find user with id {}, " + "even though returned by the native query", userId);
        } else {
            result.add(user);
        }
    }

    return result;
}

From source file:br.com.surittec.surijpa.criteria.JPQL.java

private Query getQuery() {
    Query query = entityManager.createQuery(this.toString());

    for (String paramName : params.keySet()) {
        query.setParameter(paramName, params.get(paramName));
    }//from  w  w w. jav a 2 s  . c o m

    if (firstResult != null)
        query.setFirstResult(firstResult);
    if (maxResults != null)
        query.setMaxResults(maxResults);

    return query;
}

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

public List<User> getUsersByLetter(char letter, int offset, int length) throws UserManagementException {
    List<User> users = new ArrayList<User>();
    Query query = getNamedQuery("User.findByUserIdPatternOrderByUserId");
    if (offset != 0) {
        query.setFirstResult(offset);/* w  ww  . ja va  2  s  .  c  o  m*/
    }
    if (length != -1) {
        query.setMaxResults(length);
    }
    query.setParameter("pattern", letter + "%");
    List results = query.getResultList();
    if (results != null) {
        for (Object obj : results) {
            users.add((User) obj);
        }
    }
    return users;
}

From source file:com.maomao.framework.dao.jpa.RedisDaoSupportImpl.java

/**
 * Query from db , and retrive objects from redis.
 * /*from   w  w w. ja  va2  s.c  o  m*/
 * @param jpql
 * @param params
 * @return
 */
@SuppressWarnings("unchecked")
public List<T> findList(final String jpql, final Object[] params, final int firstResult, final int maxResults) {
    StringBuffer qlwithParams = new StringBuffer(jpql.length());
    char c;
    for (int i = 0; i < jpql.length(); i++) {
        c = jpql.charAt(i);
        if (jpql.charAt(i) == '?') {
            qlwithParams.append("?" + i);
        } else
            qlwithParams.append(c);
    }

    Query query = entityManager.createQuery(jpql);
    if (params != null) {
        int idx = 1;
        for (Object o : params) {
            query.setParameter(idx++, o);
        }
    }

    if (firstResult > 0)
        query.setFirstResult(firstResult);
    if (maxResults > 0)
        query.setMaxResults(maxResults);
    final List<String> keys = query.getResultList();
    final List<T> result = new ArrayList<T>();
    jedisTemplate.execute(new JedisAction<List<T>>() {
        @Override
        public List<T> action(Jedis jedis) {
            String xml;
            T o = null;
            for (String key : keys) {
                xml = jedis.hget(POOL + entityClass.getSimpleName(), key);
                if (StringUtils.isEmpty(xml) || "<null/>".equals(xml)) {
                    o = RedisDaoSupportImpl.super.get((ID) key);
                    if (o != null) {
                        xml = x.toXML(o);
                        jedis.hset(POOL + entityClass.getSimpleName(), key, xml);
                    }
                } else {
                    o = (T) x.fromXML(xml);
                }
                result.add(o);
            }
            return result;
        }
    });

    return result;
}

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

/**
 * Note: using SuppressWarnings annotation because the JPA API is not genericized.
 *//*w w w .  j  av a2 s.c om*/
@SuppressWarnings(value = "unchecked")
public List<GroupRequest> getMembershipRequestsByGroup(Group group, int offset, int length)
        throws SocialSiteException {
    if (group == null) {
        throw new SocialSiteException("Group is null");
    }
    Query query = strategy.getNamedQuery("GroupRequest.getByGroup");
    query.setParameter(1, group);
    if (offset != 0) {
        query.setFirstResult(offset);
    }
    if (length != -1) {
        query.setMaxResults(length);
    }
    return (List<GroupRequest>) query.getResultList();
}

From source file:org.apache.oozie.executor.jpa.WorkflowsJobGetJPAExecutor.java

@SuppressWarnings("unchecked")
@Override//from  w ww.  j a  v  a 2  s .  c  o  m
public WorkflowsInfo execute(EntityManager em) throws JPAExecutorException {
    List<String> orArray = new ArrayList<String>();
    List<String> colArray = new ArrayList<String>();
    List<Object> valArray = new ArrayList<Object>();
    StringBuilder sb = new StringBuilder("");
    String orderBy = DEFAULT_ORDER_BY;
    boolean isStatus = false;
    boolean isAppName = false;
    boolean isUser = false;
    boolean isEnabled = false;
    boolean isId = false;
    int index = 0;
    for (Map.Entry<String, List<String>> entry : filter.entrySet()) {
        String colName = null;
        String colVar = null;
        if (entry.getKey().equals(OozieClient.FILTER_GROUP)) {
            XLog.getLog(getClass()).warn("Filter by 'group' is not supported anymore");
        } else {
            if (entry.getKey().equals(OozieClient.FILTER_STATUS)) {
                List<String> values = filter.get(OozieClient.FILTER_STATUS);
                colName = "status";
                for (int i = 0; i < values.size(); i++) {
                    colVar = "status";
                    colVar = colVar + index;
                    if (!isEnabled && !isStatus) {
                        sb.append(seletStr).append(" where w.statusStr IN (:status" + index);
                        isStatus = true;
                        isEnabled = true;
                    } else {
                        if (isEnabled && !isStatus) {
                            sb.append(" and w.statusStr IN (:status" + index);
                            isStatus = true;
                        } else {
                            if (isStatus) {
                                sb.append(", :status" + index);
                            }
                        }
                    }
                    if (i == values.size() - 1) {
                        sb.append(")");
                    }
                    index++;
                    valArray.add(values.get(i));
                    orArray.add(colName);
                    colArray.add(colVar);
                }
            } else {
                if (entry.getKey().equals(OozieClient.FILTER_NAME)) {
                    List<String> values = filter.get(OozieClient.FILTER_NAME);
                    colName = "appName";
                    for (int i = 0; i < values.size(); i++) {
                        colVar = "appName";
                        colVar = colVar + index;
                        if (!isEnabled && !isAppName) {
                            sb.append(seletStr).append(" where w.appName IN (:appName" + index);
                            isAppName = true;
                            isEnabled = true;
                        } else {
                            if (isEnabled && !isAppName) {
                                sb.append(" and w.appName IN (:appName" + index);
                                isAppName = true;
                            } else {
                                if (isAppName) {
                                    sb.append(", :appName" + index);
                                }
                            }
                        }
                        if (i == values.size() - 1) {
                            sb.append(")");
                        }
                        index++;
                        valArray.add(values.get(i));
                        orArray.add(colName);
                        colArray.add(colVar);
                    }
                } else {
                    if (entry.getKey().equals(OozieClient.FILTER_USER)) {
                        List<String> values = filter.get(OozieClient.FILTER_USER);
                        colName = "user";
                        for (int i = 0; i < values.size(); i++) {
                            colVar = "user";
                            colVar = colVar + index;
                            if (!isEnabled && !isUser) {
                                sb.append(seletStr).append(" where w.user IN (:user" + index);
                                isUser = true;
                                isEnabled = true;
                            } else {
                                if (isEnabled && !isUser) {
                                    sb.append(" and w.user IN (:user" + index);
                                    isUser = true;
                                } else {
                                    if (isUser) {
                                        sb.append(", :user" + index);
                                    }
                                }
                            }
                            if (i == values.size() - 1) {
                                sb.append(")");
                            }
                            index++;
                            valArray.add(values.get(i));
                            orArray.add(colName);
                            colArray.add(colVar);
                        }
                    }
                }
                if (entry.getKey().equals(OozieClient.FILTER_ID)) {
                    List<String> values = filter.get(OozieClient.FILTER_ID);
                    colName = "id";
                    for (int i = 0; i < values.size(); i++) {
                        colVar = "id";
                        colVar = colVar + index;
                        if (!isEnabled && !isId) {
                            sb.append(seletStr).append(" where w.id IN (:id" + index);
                            isId = true;
                            isEnabled = true;
                        } else {
                            if (isEnabled && !isId) {
                                sb.append(" and w.id IN (:id" + index);
                                isId = true;
                            } else {
                                if (isId) {
                                    sb.append(", :id" + index);
                                }
                            }
                        }
                        if (i == values.size() - 1) {
                            sb.append(")");
                        }
                        index++;
                        valArray.add(values.get(i));
                        orArray.add(colName);
                        colArray.add(colVar);
                    }
                } else if (entry.getKey().equalsIgnoreCase(OozieClient.FILTER_CREATED_TIME_START)) {
                    List<String> values = filter.get(OozieClient.FILTER_CREATED_TIME_START);
                    colName = "createdTimestampStart";
                    if (values.size() > 1) {
                        throw new JPAExecutorException(ErrorCode.E0302,
                                "cannot specify multiple startcreatedtime");
                    }
                    colVar = colName;
                    colVar = colVar + index;
                    if (!isEnabled) {
                        sb.append(seletStr).append(" where w.createdTimestamp >= :" + colVar);
                        isEnabled = true;
                    } else {
                        sb.append(" and w.createdTimestamp >= :" + colVar);
                    }
                    index++;
                    Date createdTime = null;
                    try {
                        createdTime = parseCreatedTimeString(values.get(0));
                    } catch (Exception e) {
                        throw new JPAExecutorException(ErrorCode.E0302, e.getMessage());
                    }
                    Timestamp createdTimeStamp = new Timestamp(createdTime.getTime());
                    valArray.add(createdTimeStamp);
                    orArray.add(colName);
                    colArray.add(colVar);

                } else if (entry.getKey().equalsIgnoreCase(OozieClient.FILTER_CREATED_TIME_END)) {
                    List<String> values = filter.get(OozieClient.FILTER_CREATED_TIME_END);
                    colName = "createdTimestampEnd";
                    if (values.size() > 1) {
                        throw new JPAExecutorException(ErrorCode.E0302,
                                "cannot specify multiple endcreatedtime");
                    }
                    colVar = colName;
                    colVar = colVar + index;
                    if (!isEnabled) {
                        sb.append(seletStr).append(" where w.createdTimestamp <= :" + colVar);
                        isEnabled = true;
                    } else {
                        sb.append(" and w.createdTimestamp <= :" + colVar);
                    }
                    index++;
                    Date createdTime = null;
                    try {
                        createdTime = parseCreatedTimeString(values.get(0));
                    } catch (Exception e) {
                        throw new JPAExecutorException(ErrorCode.E0302, e.getMessage());
                    }
                    Timestamp createdTimeStamp = new Timestamp(createdTime.getTime());
                    valArray.add(createdTimeStamp);
                    orArray.add(colName);
                    colArray.add(colVar);
                }
                // w.id = text || w.appName.contains(text) || w.user.contains(text)
                else if (entry.getKey().equalsIgnoreCase(OozieClient.FILTER_TEXT)) {
                    StoreStatusFilter.filterJobsUsingText(filter, sb, isEnabled, seletStr, valArray, orArray,
                            colArray);
                    isEnabled = true;
                }
            }
        }
    }

    orderBy = StoreStatusFilter.getSortBy(filter, orderBy);
    int realLen = 0;

    Query q = null;
    Query qTotal = null;
    if (orArray.size() == 0 && orderBy.equals(DEFAULT_ORDER_BY)) {
        q = em.createNamedQuery("GET_WORKFLOWS_COLUMNS");
        q.setFirstResult(start - 1);
        q.setMaxResults(len);
        qTotal = em.createNamedQuery("GET_WORKFLOWS_COUNT");
    } else {
        sb = sb.toString().trim().length() == 0 ? sb.append(seletStr) : sb;
        String sbTotal = sb.toString();
        sb.append(orderBy);
        q = em.createQuery(sb.toString());
        q.setFirstResult(start - 1);
        q.setMaxResults(len);
        qTotal = em.createQuery(sbTotal.replace(seletStr, countStr));

        for (int i = 0; i < orArray.size(); i++) {
            q.setParameter(colArray.get(i), valArray.get(i));
            qTotal.setParameter(colArray.get(i), valArray.get(i));
        }
    }

    OpenJPAQuery kq = OpenJPAPersistence.cast(q);
    JDBCFetchPlan fetch = (JDBCFetchPlan) kq.getFetchPlan();
    fetch.setFetchBatchSize(20);
    fetch.setResultSetType(ResultSetType.SCROLL_INSENSITIVE);
    fetch.setFetchDirection(FetchDirection.FORWARD);
    fetch.setLRSSizeAlgorithm(LRSSizeAlgorithm.LAST);
    List<?> resultList = q.getResultList();
    List<Object[]> objectArrList = (List<Object[]>) resultList;
    List<WorkflowJobBean> wfBeansList = new ArrayList<WorkflowJobBean>();

    for (Object[] arr : objectArrList) {
        WorkflowJobBean ww = getBeanForWorkflowFromArray(arr);
        wfBeansList.add(ww);
    }

    realLen = ((Long) qTotal.getSingleResult()).intValue();

    return new WorkflowsInfo(wfBeansList, start, len, realLen);
}

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

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

From source file:org.tolven.analysis.bean.SnapshotBean.java

@Override
public MenuData findMenuData(long id, Account account) {
    Query query = em
            .createQuery("SELECT md FROM MenuData md WHERE " + "md.id = :id AND " + "md.account.id = :account");
    query.setParameter("id", id);
    query.setParameter("account", account.getId());
    query.setMaxResults(1);
    List<MenuData> results = query.getResultList();
    if (results.size() == 0) {
        return null;
    } else if (results.size() == 1) {
        return results.get(0);
    } else {//from ww  w.  ja  va 2 s. c  om
        throw new RuntimeException(
                "Found more than one active MenuData with id: " + id + " in account: " + account.getId());
    }
}