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:com.haulmont.cuba.core.app.RdbmsStore.java

@SuppressWarnings("unchecked")
protected <E extends Entity> List<E> getResultListIteratively(LoadContext<E> context, Query query,
        Collection<E> filteredCollection, int initialSize, boolean needApplyConstraints) {
    int requestedFirst = context.getQuery().getFirstResult();
    int requestedMax = context.getQuery().getMaxResults();

    if (requestedMax == 0) {
        // set contains all items if query without paging
        return new ArrayList<>(filteredCollection);
    }/*from w w  w  .j ava  2  s  . c  o m*/

    int setSize = initialSize + requestedFirst;
    int factor = filteredCollection.size() == 0 ? 2 : initialSize / filteredCollection.size() * 2;

    filteredCollection.clear();

    int firstResult = 0;
    int maxResults = (requestedFirst + requestedMax) * factor;
    int i = 0;
    while (filteredCollection.size() < setSize) {
        if (i++ > 10000) {
            log.warn("In-memory distinct: endless loop detected for " + context);
            break;
        }
        query.setFirstResult(firstResult);
        query.setMaxResults(maxResults);
        //noinspection unchecked
        List<E> list = query.getResultList();
        if (list.size() == 0) {
            break;
        }
        if (needApplyConstraints) {
            security.filterByConstraints((Collection<Entity>) list);
        }
        filteredCollection.addAll(list);

        firstResult = firstResult + maxResults;
    }

    // Copy by iteration because subList() returns non-serializable class
    int max = Math.min(requestedFirst + requestedMax, filteredCollection.size());
    List<E> result = new ArrayList<>(max - requestedFirst);
    int j = 0;
    for (E item : filteredCollection) {
        if (j >= max)
            break;
        if (j >= requestedFirst)
            result.add(item);
        j++;
    }
    return result;
}

From source file:com.gettec.fsnip.fsn.dao.product.impl.ProductDAOImpl.java

/**
 * ???//from  w  w w .j a  va  2  s.c o m
 * @author tangxin 2015-05-05
 */
@SuppressWarnings("unchecked")
@Override
public List<DetailAlbumVO> getProductAlbums(Long organization, int page, int pageSize, String cut)
        throws DaoException {
    try {
        String sql = "SELECT pd.id,pd.`name`,tm0.URL,pd.format,pd.des,tm1.censcon1,tm2.censcon2,tm3.censcon3,pd.riskIndex FROM product pd "
                + "LEFT JOIN (SELECT tt.id,tt.URL,tt.UPLOAD_DATE FROM (SELECT pr.id,res.URL,res.UPLOAD_DATE FROM product pr "
                + "LEFT JOIN t_test_product_to_resource t2p ON pr.id = t2p.PRODUCT_ID "
                + "LEFT JOIN t_test_resource res ON t2p.RESOURCE_ID = res.RESOURCE_ID "
                + "WHERE pr.organization = :organization ORDER BY res.UPLOAD_DATE DESC) tt GROUP BY tt.id ORDER BY tt.id DESC) tm0 ON pd.id = tm0.id "
                +

                "LEFT JOIN (SELECT pro.id,count(tr.id) 'censcon1' FROM product pro "
                + "LEFT JOIN product_instance pi ON pro.id = pi.product_id "
                + "LEFT JOIN test_result tr ON pi.id = tr.sample_id "
                + "where pro.organization = :organization AND tr.publish_flag = 1 and tr.test_type = '??' GROUP BY pro.id) tm1 ON pd.id = tm1.id "
                +

                "LEFT JOIN (SELECT pro.id,count(tr.id) 'censcon2' FROM product pro "
                + "LEFT JOIN product_instance pi ON pro.id = pi.product_id "
                + "LEFT JOIN test_result tr ON pi.id = tr.sample_id "
                + "where pro.organization = :organization AND tr.publish_flag = 1 and tr.test_type = '' GROUP BY pro.id) tm2 ON pd.id = tm2.id "
                +

                "LEFT JOIN (SELECT pro.id,count(tr.id) 'censcon3' FROM product pro "
                + "LEFT JOIN product_instance pi ON pro.id = pi.product_id "
                + "LEFT JOIN test_result tr ON pi.id = tr.sample_id "
                + "where pro.organization = :organization AND tr.publish_flag = 1 and tr.test_type = '?' GROUP BY pro.id) tm3 ON pd.id = tm3.id "
                +

                " where pd.organization = :organization ORDER BY pd.id DESC";
        Query query = entityManager.createNativeQuery(sql);
        if (page > 0 && pageSize > 0) {
            page = (page - 1) * pageSize;
            query.setFirstResult(page);
            query.setMaxResults(pageSize);
        }
        query.setParameter("organization", organization);
        List<Object[]> listProduct = query.getResultList();
        return createDetailAlbumVO(listProduct, cut);
    } catch (Exception e) {
        throw new DaoException(e.getMessage(), e);
    }
}

From source file:br.org.indt.ndg.server.survey.SurveyHandlerBean.java

public QueryInputOutputVO getImeisBySurvey(String surveyId, String status, QueryInputOutputVO queryIOVO)
        throws MSMApplicationException {
    if (queryIOVO == null) {
        queryIOVO = new QueryInputOutputVO();
    }/*from   w  ww .j  a  v  a  2s.c o m*/

    String sQuery = "from Transactionlog where transactionType = ";
    sQuery += "\'";
    sQuery += TransactionLogVO.TYPE_SEND_SURVEY;
    sQuery += "\'";
    sQuery += " and survey.idSurvey = :surveyId and transactionStatus = :status";

    // PENDING is all that was not downloaded yet (may be PENDING or
    // AVAILABLE, any status that is not SUCCESS)
    if ((status != null) && status.equals(TransactionLogVO.STATUS_PENDING)) {
        sQuery = "";
        sQuery += "from Transactionlog where transactionType = ";
        sQuery += "\'";
        sQuery += TransactionLogVO.TYPE_SEND_SURVEY;
        sQuery += "\'";
        sQuery += " and survey.idSurvey = :surveyId and NOT(transactionStatus = " + "\'"
                + TransactionLogVO.STATUS_SUCCESS + "\')";
    }

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

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

    Query q = manager.createQuery(sQuery);

    q.setParameter("surveyId", surveyId);

    // if it is not PENDING 'status' parameter is used
    if ((status != null) && (!status.equals(TransactionLogVO.STATUS_PENDING))) {
        q.setParameter("status", status);
    }

    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> ret = new ArrayList<Object>();
    ArrayList<Transactionlog> al = (ArrayList<Transactionlog>) q.getResultList();

    Iterator<Transactionlog> it = al.iterator();

    while (it.hasNext()) {
        Transactionlog surveyTransactionLog = (Transactionlog) it.next();

        Imei imei = null;

        if (surveyTransactionLog.getImei() != null) {
            imei = manager.find(Imei.class, surveyTransactionLog.getImei().getImei());
            System.out.println("####### SurveyTransactionLog: IMEI = " + surveyTransactionLog.getImei());
        }

        if (imei != null) {
            ImeiVO vo = new ImeiVO();
            vo.setImei(imei.getImei());
            vo.setMsisdn(imei.getMsisdn());
            vo.setUserName(imei.getUser().getUsername());
            NdgDevice device = imei.getDevice();
            DeviceVO devVO = new DeviceVO();
            devVO.setIdDevice(device.getIdDevice());
            devVO.setDeviceModel(device.getDeviceModel());
            vo.setDevice(devVO);
            vo.setRealImei(imei.getRealImei());

            if (!surveyTransactionLog.getTransactionStatus().equals(TransactionLogVO.STATUS_SUCCESS)) {
                vo.setStatus(TransactionLogVO.STATUS_PENDING);
            } else {
                vo.setStatus(surveyTransactionLog.getTransactionStatus());
            }

            ret.add(vo);
        }

    }

    queryIOVO.setQueryResult(ret);

    return queryIOVO;
}

From source file:org.j2free.jpa.Controller.java

/**
 * @param <T> The type of entity to fetch
 * @param entityClass The class of the entity to fetch
 * @param start The first entity to fetch
 * @param limit How many entities to fetch
 * @return a <tt>List</tt> of entities found
 *///from www .  jav a  2s  . c  om
public <T> List<T> list(Class<T> entityClass, int start, int limit) {
    Query query = em.createQuery("SELECT e FROM " + entityClass.getSimpleName() + " e");

    if (start > 0) {
        query.setFirstResult(start);
    }
    if (limit > 0) {
        query.setMaxResults(limit);
    }

    return (List<T>) query.getResultList();
}

From source file:com.gettec.fsnip.fsn.dao.product.impl.ProductDAOImpl.java

@Override
public List<ProductStaVO> getProductStaListByConfigureData(Long businessId, String productName, String barcode,
        String startDate, String endDate, int page, int pageSize) {
    String sqlString = "";
    if (startDate != null && !"".equals(startDate)) {
        sqlString += " AND tr.publishDate >= '" + startDate + "' ";
    }/*from   ww w  . j a v a  2 s  .  c om*/
    if (endDate != null && !"".equals(endDate)) {
        sqlString += " AND tr.publishDate < DATE_ADD('" + endDate + "', INTERVAL 1 DAY) ";
    }
    String sql = " SELECT  ";
    //???
    sql += " (SELECT COUNT(*) FROM product_instance pri,test_result tr WHERE p.id=pri.product_id AND  tr.sample_id=pri.id AND tr.publish_flag=1 ";
    sql += " AND tr.organization = bu.organization ";
    sql += sqlString;
    sql += " ) publishReportQuantity ,";
    //???
    sql += "(SELECT COUNT(*) FROM product_instance pri,test_result tr WHERE p.id=pri.product_id AND  tr.sample_id=pri.id AND tr.publish_flag=0 ";
    sql += " AND tr.organization = bu.organization) notPublishReportQuantity ,";
    //???
    sql += " (SELECT MAX(tr.publishDate) FROM product_instance pri,test_result tr WHERE p.id=pri.product_id AND  tr.sample_id=pri.id AND tr.publish_flag=1";
    sql += " AND tr.organization = bu.organization AND tr.publishDate is not null ";
    sql += sqlString;
    sql += " ) publishDate,";
    sql += "bu.name buName,p.name productName,p.barcode,bu.organization ";
    sql += " FROM  product p ";
    sql += " LEFT JOIN business_unit bu ON  p.organization = bu.organization ";
    sql += " WHERE bu.id=:buId ";
    if (productName != null && !"".equals(productName)) {
        sql += " AND p.name LIKE '%" + productName + "%' ";
    }
    if (barcode != null && !"".equals(barcode)) {
        sql += " AND p.barcode LIKE '%" + barcode + "%'";
    }
    Query query = entityManager.createNativeQuery(sql);
    query.setParameter("buId", businessId);
    if (page > 0 && pageSize > 0) {
        query.setFirstResult((page - 1) * pageSize);
        query.setMaxResults(pageSize);
    }
    @SuppressWarnings("unchecked")
    List<Object[]> objs = query.getResultList();
    List<ProductStaVO> proList = new ArrayList<ProductStaVO>();
    try {
        for (Object[] obj : objs) {
            ProductStaVO proSta = new ProductStaVO();
            //???
            proSta.setReportQuantity(obj[0] == null ? null : Long.parseLong(obj[0].toString()));
            //???
            proSta.setNotPublishReportQuantity(obj[1] == null ? null : Long.parseLong(obj[1].toString()));
            //???
            proSta.setLastPubDate(obj[2] == null ? null : formatter.parse(obj[2].toString()));
            proSta.setBusinessName(obj[3] == null ? null : obj[3].toString());
            proSta.setProductName(obj[4] == null ? null : obj[4].toString());
            proSta.setBarcode(obj[5] == null ? null : obj[5].toString());
            proList.add(proSta);
        }
    } catch (NumberFormatException e) {
        e.printStackTrace();
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return proList;
}

From source file:com.tzquery.fsn.dao.impl.TzQueryDaoImpl.java

/**
 * ????????/*  ww  w .ja va2  s . co  m*/
 * @param paramVO
 * @return
 * @throws DaoException
  */
@Override
public List<ProcurementInfo> getRawMaterialInfoList(TzQueryRequestParamVO paramVO, int type)
        throws DaoException {
    try {
        List<ProcurementInfo> list = new ArrayList<ProcurementInfo>();
        StringBuffer sql = new StringBuffer();
        sql.append("SELECT p.* FROM procurement_info p ");
        sql.append("LEFT JOIN business_unit b ON b.organization=p.organization_id ");
        sql.append("WHERE b.`name`=?1 AND p.type=?2  ");
        if (StringUtils.isNotBlank(paramVO.getProName())) {
            sql.append(" AND  p.name LIKE ?3  ");
        }
        sql.append(" ORDER BY p.procurement_date desc ");
        Query query = entityManager.createNativeQuery(sql.toString(), ProcurementInfo.class);
        query.setParameter(1, paramVO.getBusName());
        query.setParameter(2, type);
        if (StringUtils.isNotBlank(paramVO.getProName())) {
            query.setParameter(3, "%" + paramVO.getProName() + "%");
        }
        if (paramVO.getPage() > 0 && paramVO.getPageSize() > 0) {
            query.setFirstResult((paramVO.getPage() - 1) * paramVO.getPageSize());
            query.setMaxResults(paramVO.getPageSize());
        }
        list = query.getResultList();
        return list;
    } catch (Exception e) {
        throw new DaoException(
                "TzQueryDaoImpl-->getRawMaterialInfoList()?????????", e);
    }
}

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

/**
 * {@inheritDoc}/* w  w  w .  j a  v a  2s  .c  o m*/
 */
@Override
public Page searchLinkedDocumentsTopic(String placeToSearch, String topicToSearch,
        PaginationFilter paginationFilter) throws PersistenceException {
    Page page = new Page(paginationFilter);
    Query query = null;

    String toSearch = "FROM Document WHERE entryId IN (SELECT document.entryId FROM org.medici.bia.domain.EplToLink WHERE place.placeAllId = "
            + placeToSearch;
    if (topicToSearch != null) {
        toSearch += " AND topic.topicTitle LIKE '" + topicToSearch + "'";
    }
    toSearch += ") AND logicalDelete=false";

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

    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:com.tzquery.fsn.dao.impl.TzQueryDaoImpl.java

/**
 * ?id??????//from  w  ww .jav  a 2  s  . c om
 * @param paramVO
 * @return
 * @throws DaoException
 */
@Override
public List<ProcurementDispose> getProcurementDisposeList(TzQueryRequestParamVO paramVO, int type)
        throws DaoException {
    try {
        List<ProcurementDispose> list = new ArrayList<ProcurementDispose>();
        StringBuffer sql = new StringBuffer();
        sql.append(
                "SELECT p.* FROM procurement_dispose p LEFT JOIN business_unit b ON b.organization=p.organization_id  WHERE b.name=?1 AND p.type=?2 ");
        if (StringUtils.isNotBlank(paramVO.getProName())) {
            sql.append(" AND  p.procurement_name LIKE ?3  ");
        }
        sql.append(" ORDER BY dispose_date desc ");
        Query query = entityManager.createNativeQuery(sql.toString(), ProcurementDispose.class);
        query.setParameter(1, paramVO.getBusName());
        query.setParameter(2, type);
        if (StringUtils.isNotBlank(paramVO.getProName())) {
            query.setParameter(3, "%" + paramVO.getProName() + "%");
        }
        if (paramVO.getPage() > 0 && paramVO.getPageSize() > 0) {
            query.setFirstResult((paramVO.getPage() - 1) * paramVO.getPageSize());
            query.setMaxResults(paramVO.getPageSize());
        }
        list = query.getResultList();
        return list;
    } catch (Exception e) {
        throw new DaoException(
                "TzQueryDaoImpl-->getProcurementDisposeList()?id???????",
                e);
    }
}

From source file:com.gettec.fsnip.fsn.dao.product.impl.ProductDAOImpl.java

/**
 * ???/*from  ww  w .  ja va2s  .c om*/
 * @param page 
 * @param size 
 * @param organization 
 * @return
 * @throws DaoException 
 */
@SuppressWarnings("unchecked")
@Override
public List<Product> getAllLocalProduct(int page, int size, Long organization) throws DaoException {
    try {
        String sql = "SELECT DISTINCT p.* FROM product p " + "Inner JOIN business_unit b ON p.producer_id=b.id "
                + "LEFT JOIN t_meta_initialize_product t ON p.id=t.product_id AND t.organization=?1 "
                + "WHERE b.organization=?2 AND t.first_storage_id is NULL ";

        Query query = entityManager.createNativeQuery(sql.toString(), Product.class);
        query.setParameter(1, organization);
        query.setParameter(2, organization);
        if (page > 0) {
            query.setFirstResult((page - 1) * size);
            query.setMaxResults(size);
        }
        List<Product> result = query.getResultList();
        return result;
    } catch (Exception e) {
        throw new DaoException(
                "ProductDAOImpl.getAllLocalProduct() ???,?",
                e);
    }
}

From source file:it.webappcommon.lib.jpa.ControllerStandard.java

/**
 * /*from  ww w  .  ja v  a 2 s  .  c o  m*/
 * Metodo che restituisce una collezione di oggetti specificati come
 * parametro, tramite la query da lanciare, la mappa dei parametri,
 * l'elemento di inizio e il numero di elementi desiderati (mettendo a 0
 * questo parametro li restituisce tutti)
 * 
 * @param classObj
 * @param query
 * @param map
 * @param firstItem
 * @param batchSize
 * @return
 * @throws java.lang.Exception
 */
public <T extends EntityBaseStandard> List<T> findListCustomQuery(Class<T> classObj, String query,
        Map<String, Object> map, int firstItem, int batchSize) throws Exception {
    List<T> returnValue = null;

    EntityManagerFactory emf = null;
    EntityManager em = null;
    Map.Entry entry = null;
    Iterator i = null;
    Query q = null;
    try {
        /* Istanzio l'entity manager */
        emf = getEntityManagerFactory();
        em = emf.createEntityManager();

        /* Genero la query */
        q = em.createQuery(query);

        /*
         * Se il numero di elementi  diverso da 0 specifico quanti e da
         * dove cominciare
         */
        if (batchSize > 0) {
            q.setFirstResult(firstItem);
            q.setMaxResults(batchSize);
        }

        /* Verifico la validit della mappa */
        if (map != null) {
            /* Per ogni elemento della mappa setto il parametro */
            for (i = map.entrySet().iterator(); i.hasNext();) {
                entry = (Map.Entry) i.next();
                q.setParameter((String) entry.getKey(), entry.getValue());
            }
        }

        /* Calcolo la collezione di elementi desiderati */
        returnValue = (List<T>) q.getResultList();
    } catch (Exception e) {
        throw e;
    } finally {
        if (!passedEm) {
            PersistenceManagerUtil.close(em);
        }
        entry = null;
        em = null;
        q = null;
        i = null;
    }
    return returnValue;
}