Example usage for javax.persistence Query setFirstResult

List of usage examples for javax.persistence Query setFirstResult

Introduction

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

Prototype

Query setFirstResult(int startPosition);

Source Link

Document

Set the position of the first result to retrieve.

Usage

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

public Report getReport(int offset, int limit) {
    Report report = new ReportImpl();
    report.setLimit(limit);/*from   w w  w.j  av  a2 s. co m*/
    report.setOffset(offset);

    EntityManager em = null;
    try {
        em = emf.createEntityManager();
        Query q = em.createNamedQuery("countSessionsGroupByMediapackage");
        q.setFirstResult(offset);
        q.setMaxResults(limit);

        @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:com.maomao.framework.dao.jpa.RedisDaoSupportImpl.java

/**
 * Query from db , and retrive objects from redis.
 * /*from  www  .ja v a 2 s.co 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.
 *///from w  w  w .j a  v  a2s . c om
@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:com.sun.socialsite.business.impl.JPAGroupManagerImpl.java

/**
 * Note: using SuppressWarnings annotation because the JPA API is not genericized.
 *///www .  j  ava 2  s  . c  om
@SuppressWarnings(value = "unchecked")
public List<GroupRelationship> getMembershipsByProfile(Profile profile, int offset, int length)
        throws SocialSiteException {
    Query query = strategy.getNamedQuery("GroupRelationship.getByUserProfile");
    query.setParameter(1, profile);
    if (offset != 0) {
        query.setFirstResult(offset);
    }
    if (length != -1) {
        query.setMaxResults(length);
    }
    return (List<GroupRelationship>) query.getResultList();
}

From source file:org.opentides.dao.impl.BaseEntityDaoJpaImpl.java

/**
 * {@inheritDoc}//from w  w  w  .j  a  v a  2 s. c om
 */
@Override
@SuppressWarnings("unchecked")
public final List<T> findByExample(final T example, boolean exactMatch, int start, int total) {
    String joinClause = appendJoinToExample(example);
    String whereClause = CrudUtil.buildJpaQueryString(example, exactMatch);
    String orderClause = " " + appendOrderToExample(example);
    String filterClause = this.buildSecurityFilterClause(example);
    String append = appendClauseToExample(example, exactMatch);
    whereClause = doSQLAppend(whereClause, append);
    whereClause = doSQLAppend(whereClause, filterClause);
    if (_log.isDebugEnabled())
        _log.debug("QBE >> " + whereClause + orderClause);
    String sql = "select (obj) from " + getEntityBeanType().getName() + " obj " + joinClause + whereClause
            + orderClause;
    Query query = getEntityManager().createQuery(sql);
    setQueryParameters(query, sql, example);
    setHints(example, query);
    if (start > -1)
        query.setFirstResult(start);
    if (total > -1)
        query.setMaxResults(total);
    return query.getResultList();
}

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

@SuppressWarnings("unchecked")
public UserActionList getUserActionsByType(String type, int offset, int limit) {
    UserActionList result = new UserActionListImpl();

    result.setTotal(getTotal(type));//from  w ww  . ja  v a  2  s  .  c om
    result.setOffset(offset);
    result.setLimit(limit);

    EntityManager em = null;
    try {
        em = emf.createEntityManager();
        Query q = em.createNamedQuery("findUserActionsByType");
        q.setParameter("type", type);
        q.setFirstResult(offset);
        q.setMaxResults(limit);
        Collection<UserAction> userActions = q.getResultList();

        for (UserAction a : userActions) {
            result.add(a);
        }
        return result;
    } finally {
        if (em != null && em.isOpen()) {
            em.close();
        }
    }
}

From source file:com.music.dao.Dao.java

@SuppressWarnings("unchecked")
protected <T> List<T> findByQuery(QueryDetails details) {
    Query q = null;
    if (details.getQueryName() != null) {
        q = entityManager.createNamedQuery(details.getQueryName());
    } else if (details.getQuery() != null) {
        q = entityManager.createQuery(details.getQuery());
    } else {//  ww w  .java  2 s . co m
        throw new IllegalArgumentException("Either query or query name must be set");
    }

    for (int i = 0; i < details.getParamNames().length; i++) {
        q.setParameter(details.getParamNames()[i], details.getParamValues()[i]);
    }
    if (details.getStart() > -1) {
        q.setFirstResult(details.getStart());
    }
    if (details.getCount() > -1) {
        q.setMaxResults(details.getCount());
    }
    if (details.isCacheable()) {
        setCacheable(q);
    }
    return q.getResultList();
}

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);/*  w ww  .j  av a 2  s  .  co 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.apache.oozie.executor.jpa.WorkflowsJobGetJPAExecutor.java

@SuppressWarnings("unchecked")
@Override/*from  ww  w. j  a v a  2s .  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:net.firejack.platform.core.store.BaseStore.java

private Query getNamedQuery(Session session, String queryName, Integer offset, Integer limit) {
    Query query = session.getNamedQuery(queryName);
    if (offset != null && offset > -1) {
        query.setFirstResult(offset);
    }//from w  ww .  j  a  v  a 2s.  co  m
    if (limit != null && limit > -1) {
        query.setMaxResults(limit);
    }
    return query;
}