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

/**
 * ?sql//w w w .  j a va  2  s.c om
 * @author ChenXiaolin 2015-12-03
 * @param paramVO 
 * @param sql 
 * @return
 */
@SuppressWarnings("unchecked")
private List<TzQueryResponseTansDetailVO> excuteSqlToTransDetail(String sql, TzQueryRequestParamVO paramVO)
        throws DaoException {
    try {
        Query query = entityManager.createNativeQuery(sql);
        query.setParameter(1, paramVO.getProId());
        query.setParameter(2, paramVO.getBusId());
        query.setParameter(3, paramVO.getProId());
        query.setParameter(4, paramVO.getBusId());
        if (paramVO.getPage() > 0 && paramVO.getPageSize() > 0) {
            query.setFirstResult((paramVO.getPage() - 1) * paramVO.getPageSize());
            query.setMaxResults(paramVO.getPageSize());
        }
        List<Object[]> objects = query.getResultList();
        return setTransDetail(objects);
    } catch (Exception e) {
        throw new DaoException(
                "TzQueryDaoImpl-->excuteSqlToTransDetail()?sql,?",
                e);
    }
}

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

/**
 * @inheritDoc//from w  ww .j  a  v  a2 s.  co  m
 */
public List getWeblogEntries(Weblog website, User user, Date startDate, Date endDate, String catName, List tags,
        String status, String text, String sortby, String sortOrder, String locale, int offset, int length)
        throws WebloggerException {

    WeblogCategory cat = null;
    if (StringUtils.isNotEmpty(catName) && website != null) {
        cat = getWeblogCategoryByPath(website, catName);
        if (cat == null)
            catName = null;
    }
    if (catName != null && catName.trim().equals("/")) {
        catName = null;
    }

    List params = new ArrayList();
    int size = 0;
    StringBuffer queryString = new StringBuffer();

    //queryString.append("SELECT e FROM WeblogEntry e WHERE ");
    if (tags == null || tags.size() == 0) {
        queryString.append("SELECT e FROM WeblogEntry e WHERE ");
    } else {
        queryString.append("SELECT e FROM WeblogEntry e JOIN e.tags t WHERE ");
        queryString.append("(");
        for (int i = 0; i < tags.size(); i++) {
            if (i != 0)
                queryString.append(" OR ");
            params.add(size++, tags.get(i));
            queryString.append(" t.name = ?").append(size);
        }
        queryString.append(") AND ");
    }

    if (website != null) {
        params.add(size++, website.getId());
        queryString.append("e.website.id = ?").append(size);
    } else {
        params.add(size++, Boolean.TRUE);
        queryString.append("e.website.enabled = ?").append(size);
    }

    /*if (tags != null && tags.size() > 0) {
    // A JOIN with WeblogEntryTag in parent quert will cause a DISTINCT in SELECT clause
    // WeblogEntry has a clob field and many databases do not link DISTINCT for CLOB fields
    // Hence as a workaround using corelated EXISTS query.
    queryString.append(" AND EXISTS (SELECT t FROM WeblogEntryTag t WHERE "
            + " t.weblogEntry = e AND t.name IN (");
    final String PARAM_SEPERATOR = ", ";
    for(int i = 0; i < tags.size(); i++) {
        params.add(size++, tags.get(i));
        queryString.append("?").append(size).append(PARAM_SEPERATOR);
    }
    // Remove the trailing PARAM_SEPERATOR
    queryString.delete(queryString.length() - PARAM_SEPERATOR.length(),
            queryString.length());
            
    // Close the brace FOR IN clause and EXIST clause
    queryString.append(" ) )");
    }*/

    if (user != null) {
        params.add(size++, user.getUserName());
        queryString.append(" AND e.creatorUserName = ?").append(size);
    }

    if (startDate != null) {
        Timestamp start = new Timestamp(startDate.getTime());
        params.add(size++, start);
        queryString.append(" AND e.pubTime >= ?").append(size);
    }

    if (endDate != null) {
        Timestamp end = new Timestamp(endDate.getTime());
        params.add(size++, end);
        queryString.append(" AND e.pubTime <= ?").append(size);
    }

    if (cat != null && website != null) {
        params.add(size++, cat.getId());
        queryString.append(" AND e.category.id = ?").append(size);
    }

    if (status != null) {
        params.add(size++, status);
        queryString.append(" AND e.status = ?").append(size);
    }

    if (locale != null) {
        params.add(size++, locale + '%');
        queryString.append(" AND e.locale like ?").append(size);
    }

    if (text != null) {
        params.add(size++, '%' + text + '%');
        queryString.append(" AND ( e.text LIKE ?").append(size);
        queryString.append("    OR e.summary LIKE ? ").append(size);
        queryString.append("    OR e.title LIKE ?").append(size);
        queryString.append(") ");
    }

    if (sortby != null && sortby.equals("updateTime")) {
        queryString.append(" ORDER BY e.updateTime ");
    } else {
        queryString.append(" ORDER BY e.pubTime ");
    }

    if (sortOrder != null && sortOrder.equals(ASCENDING)) {
        queryString.append("ASC ");
    } else {
        queryString.append("DESC ");
    }

    Query query = strategy.getDynamicQuery(queryString.toString());
    for (int i = 0; i < params.size(); i++) {
        query.setParameter(i + 1, params.get(i));
    }

    if (offset != 0) {
        query.setFirstResult(offset);
    }
    if (length != -1) {
        query.setMaxResults(length);
    }

    return query.getResultList();
}

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

/**
 * ???/*w ww . j ava 2  s . c  o  m*/
 * @param page 
 * @param size 
 * @param organization 
 * @return
 * @throws DaoException 
 */
@SuppressWarnings("unchecked")
@Override
public List<Product> getAllNotLocalProduct(int page, int size, Long organization) throws DaoException {
    try {
        String sql = "SELECT  p.* FROM product p "
                + "RIGHT JOIN t_meta_initialize_product t ON p.id=t.product_id "
                + "WHERE t.`local`=0 AND t.first_storage_id IS NULL AND t.organization=?1";
        Query query = entityManager.createNativeQuery(sql.toString(), Product.class);
        query.setParameter(1, 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.getAllNotLocalProduct() ????",
                e);
    }
}

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 + "' ";
    }// w w  w  .  j  a  va2s  . c o m
    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

/**
 * ??????//from   w w  w. j av a 2  s  . c  o m
 * @param paramVO
 * @return
 * @throws DaoException
 */
@Override
public List<FacilityInfo> getFacilityInfoList(TzQueryRequestParamVO paramVO) throws DaoException {
    try {
        List<FacilityInfo> list = new ArrayList<FacilityInfo>();
        StringBuffer sql = new StringBuffer();
        sql.append("SELECT f.* FROM facility_info f LEFT JOIN business_unit b ON f.business_id=b.id ");
        sql.append("WHERE b.`name`=?1 ");
        if (StringUtils.isNotBlank(paramVO.getProName())) {
            sql.append(" AND f.facility_name LIKE ?2 ");
        }
        sql.append(" ORDER BY f.buying_time desc ");
        Query query = entityManager.createNativeQuery(sql.toString(), FacilityInfo.class);
        query.setParameter(1, paramVO.getBusName());
        if (StringUtils.isNotBlank(paramVO.getProName())) {
            query.setParameter(2, "%" + 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-->getFacilityInfoList()???????", e);
    }
}

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  w  w  w .  j a  v  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:it.webappcommon.lib.jpa.ControllerStandard.java

/**
 * //w  w w  .j a  v  a 2s  .  c  om
 * 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;
}

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

/**
 * //from  w ww .  j a va2s.  com
 * 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> findList2(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.createNamedQuery(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;
}

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

/**
 * {@inheritDoc}/*  w  w w . ja v a2 s  .  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: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();
    }//  ww  w . ja  v a  2s  .  com

    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;
}