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.gettec.fsnip.fsn.dao.product.impl.ProductDAOImpl.java

/**
 * ??//from   www  .  jav a  2  s  . c  o  m
 * @return Long
 * @author ZhaWanNeng<br>
  * 
  * 2015/4/10
 */
@SuppressWarnings("unchecked")
public List<ProductListVo> getProductList(Long type, int pageSize, int page) throws DaoException {
    try {
        String sql = "";
        if (type == 3 || type == 5) {
            String nrv = "0.3";
            if (type == 3) {
                nrv = "0.1";
            }
            sql = " SELECT t.id,t.pname,t.pimg,t.nname,t.nvalue,t.nunit,t.nnrv,t.nper from ("
                    + " SELECT DISTINCT pro.id as id,pro.name as pname,pro.imgUrl as pimg,nr.`name` as nname,nr.value as nvalue,nr.unit as nunit,nr.nrv as nnrv,nr.per as nper "
                    + " FROM product pro LEFT JOIN nutri_rpt nr ON nr.product_id = pro.id "
                    + " WHERE nr.nutri_id =?1 and nr.per='?100' and nr.nrv!='' and nr.nrv!='0' and nr.nrv!='0%' and nr.nrv > "
                    + nrv + " ORDER BY cast(nr.nrv as decimal(10,2)) ASC ) t  ";
        } else {
            sql = " SELECT t.id,t.pname,t.pimg,t.nname,t.nvalue,t.nunit,t.nnrv,t.nper from ("
                    + " SELECT DISTINCT pro.id as id,pro.name as pname,pro.imgUrl as pimg,nr.`name` as nname,nr.value as nvalue,nr.unit as nunit,nr.nrv as nnrv,nr.per as nper "
                    + " FROM product pro LEFT JOIN nutri_rpt nr ON nr.product_id = pro.id "
                    + " WHERE nr.nutri_id =?1 and nr.per='?100' and nr.nrv!='' ORDER BY cast(nr.nrv as decimal(10,2)) DESC ) t  ";
        }
        Query query = entityManager.createNativeQuery(sql);
        query.setParameter(1, type);
        query.setFirstResult((page - 1) * pageSize);
        query.setMaxResults(pageSize);

        List<Object[]> result = query.getResultList();
        List<ProductListVo> productListVo = new ArrayList<ProductListVo>();
        if (result.size() <= 0) {
            return null;
        }
        for (Object[] obj : result) {
            ProductNutritionVO vutrition = new ProductNutritionVO();
            Long productid = Long.valueOf(obj[0].toString());
            String productName = obj[1] != null ? obj[1].toString() : "";
            String imgUrl = obj[2] != null ? obj[2].toString() : "";
            String name = obj[3] != null ? obj[3].toString() : "";
            String value = obj[4] != null ? obj[4].toString() : "";
            String unit = obj[5] != null ? obj[5].toString() : "";
            String nrv = obj[6] != null ? obj[6].toString() : "";
            String per = obj[7] != null ? obj[7].toString() : "";
            vutrition.setName(name);
            vutrition.setNrv(nrv);
            vutrition.setPer(per);
            vutrition.setUnit(unit);
            vutrition.setValue(value);
            ProductListVo listVo = new ProductListVo(productid, productName, imgUrl, vutrition);
            productListVo.add(listVo);
        }
        return productListVo;
    } catch (Exception e) {
        throw new DaoException("ProductDAOImpl.productCount() ", e);
    }
}

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

/**
 * ?/* w  w  w  .  j a  v a  2s  .co  m*/
 * @return Long
 * @author ZhaWanNeng<br>
  * 
  * 2015/4/10
 */
@SuppressWarnings("unchecked")
public List<ProductRiskVo> riskBillboard(String type, int pageSize, int page) throws DaoException {
    try {
        String sql = "";
        if ("14".equals(type) || "10".equals(type) || "01".equals(type)) {
            sql = " SELECT DISTINCT pro.id,pro.riskIndex,pro.name,pro.imgUrl,pro.test_property_name,pro.risk_succeed FROM product pro "
                    + " WHERE pro.category LIKE '" + type
                    + "_%' and pro.risk_succeed=1 ORDER BY pro.riskIndex ASC ";
        } else if ("00".equals(type)) {
            sql = " SELECT DISTINCT pro.id,pro.riskIndex,pro.name,pro.imgUrl,pro.test_property_name,pro.risk_succeed FROM product pro "
                    + " WHERE pro.category not LIKE '14_%' and pro.category not LIKE '10_%' and  pro.category not LIKE '01_%' and pro.risk_succeed=1 ORDER BY pro.riskIndex ASC ";
        } else {
            return null;
        }
        Query query = entityManager.createNativeQuery(sql);
        //         query.setParameter(1, type);
        query.setFirstResult((page - 1) * pageSize);
        query.setMaxResults(pageSize);
        List<Object[]> result = query.getResultList();
        List<ProductRiskVo> productList = new ArrayList<ProductRiskVo>();
        if (result.size() <= 0) {
            return null;
        }
        for (Object[] obj : result) {
            Long id = Long.valueOf(obj[0].toString());
            String riskIndex = obj[1] != null ? obj[1].toString() : "";
            String name = obj[2] != null ? obj[2].toString() : "";
            String imgUrl = obj[3] != null ? obj[3].toString() : "";
            String testPropertyName = obj[4] != null ? obj[4].toString() : "";
            String tes = obj[5] != null ? obj[5].toString() : "";
            Boolean riskSucceed = false;
            if (tes.equals("true")) {
                riskSucceed = true;
            }
            ProductRiskVo productRisk = new ProductRiskVo(id, name, imgUrl, riskIndex, testPropertyName,
                    riskSucceed);
            productList.add(productRisk);
        }
        return productList;
    } catch (Exception e) {
        throw new DaoException("ProductDAOImpl.riskBillboard() ", e);
    }
}

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

/**
 * // ww w .  j  a va  2  s  . c om
 * @param <T>
 * @param collection
 * @param filterString
 * @param start
 * @param limit
 * @return
 */
public <T> List filter(Collection<T> collection, String filterString, int start, int limit) {
    org.hibernate.Query query = getSession().createFilter(collection, filterString).setFirstResult(start);
    if (limit > 0) {
        query.setMaxResults(limit);
    }

    return query.list();
}

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

/**
 * {@inheritDoc}//from w w  w.j av  a 2s .c o  m
 */
@Override
public Page searchLinkedDocumentsTopic(Integer topicId, Integer placeAllId, 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.geogKey IN (SELECT geogKey FROM Place WHERE placeAllId = "
            + placeAllId + ") AND topic.topicId = " + topicId + ") 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:org.j2free.jpa.Controller.java

/**
 *
 * @param <T>/* w  w  w .j a  va2s. c  o  m*/
 * @param collection
 * @param filterString
 * @param start
 * @param limit
 * @param params
 * @return
 */
public <T> List filter(Collection<T> collection, String filterString, int start, int limit,
        KeyValuePair<String, ? extends Object>... params) {
    org.hibernate.Query query = getSession().createFilter(collection, filterString).setFirstResult(start);
    if (limit > 0) {
        query.setMaxResults(limit);
    }

    for (KeyValuePair<String, ? extends Object> param : params) {
        query.setParameter(param.key, param.value);
    }

    return query.list();
}

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

/**
 * ???????//from   w ww  .  j ava  2s  .  c om
 * @param condition 
 * @param page
 * @param pageSize
 * @return List<String>
 * @throws DaoException
 * @author LongXianZhen
 */
@SuppressWarnings("unchecked")
@Override
public List<String> getBarcodeListByCondition(String condition, int page, int pageSize) throws DaoException {
    try {
        List<String> barcodes = null;
        if (StringUtils.isNotBlank(condition)) {
            String sql = "select barcode from product where barcode like :barcode ";
            Query query = entityManager.createNativeQuery(sql).setParameter("barcode", "%" + condition + "%");
            if (page > 0) {
                query.setFirstResult((page - 1) * pageSize);
                query.setMaxResults(pageSize);
            }
            barcodes = query.getResultList();
        }
        return barcodes;
    } catch (Exception e) {
        throw new DaoException(
                "ProductDAOImpl.getBarcodeListByCondition()???????, ?",
                e);
    }
}

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  a v a  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.sun.socialsite.userapi.UserManagerImpl.java

public List<User> getUsers(Boolean enabled, Date startDate, Date endDate, int offset, int length)
        throws UserManagementException {
    if (endDate == null) {
        endDate = new Date();
    }/*w ww  .java 2  s .  c o  m*/

    List<User> users = new ArrayList<User>();
    Query query = null;
    if (enabled != null) {
        if (startDate != null) {
            query = getNamedQuery("User.findByEnabled&StartDate&EndDateOrderByCreationDateDESC");
            query.setParameter("enabled", enabled);
            query.setParameter("startDate", startDate, TemporalType.DATE);
            query.setParameter("endDate", endDate, TemporalType.DATE);
        } else {
            query = getNamedQuery("User.findByEnabled&EndDateOrderByCreationDateDESC");
            query.setParameter("enabled", enabled);
            query.setParameter("endDate", endDate, TemporalType.DATE);
        }
    } else {
        if (startDate != null) {
            query = getNamedQuery("User.findByStartDate&EndDateOrderByCreationDateDESC");
            query.setParameter("startDate", startDate, TemporalType.DATE);
            query.setParameter("endDate", endDate, TemporalType.DATE);
        } else {
            query = getNamedQuery("User.findByEndDateOrderByCreationDateDESC");
            query.setParameter("endDate", endDate, TemporalType.DATE);
        }
    }
    if (offset != 0) {
        query.setFirstResult(offset);
    }
    if (length != -1) {
        query.setMaxResults(length);
    }
    List results = query.getResultList();
    if (results != null) {
        for (Object obj : results) {
            users.add((User) obj);
        }
    }
    return users;
}

From source file:org.hoteia.qalingo.core.dao.RetailerDao.java

public List<GeolocatedStore> findB2BStoresByGeoloc(final String countryCode, final Long productBrandId,
        final List<String> types, final String latitude, final String longitude, final String distance,
        int maxResults, Object... params) {
    if (StringUtils.isNotEmpty(latitude) && StringUtils.isNotEmpty(longitude)) {
        Float latitudeFloat = new Float(latitude);
        Float longitudeFloat = new Float(longitude);
        StringBuilder queryString = buildSQLStoresByGeoloc(countryCode, productBrandId, types, latitude,
                longitude, distance, maxResults, params);
        queryString.append("AND is_b2b = :b2b ");

        if (distance != null) {
            queryString.append("HAVING distance <= :distanceValue ");
        } else {//w ww  .j ava  2s .com
            queryString.append("HAVING distance IS NOT null ");
        }
        queryString.append("ORDER BY distance ASC");

        Query query = createNativeQuery(queryString.toString());
        query.setParameter("latitude", latitudeFloat);
        query.setParameter("longitude", longitudeFloat);
        query.setParameter("countryCode", countryCode);
        if (distance != null) {
            query.setParameter("distanceValue", distance);
        }
        query.setParameter("b2b", true);
        if (StringUtils.isNotEmpty(countryCode)) {
            query.setParameter("countryCode", countryCode);
        }
        if (productBrandId != null) {
            query.setParameter("productBrandId", productBrandId);
        }
        if (types != null && !types.isEmpty()) {
            int count = 1;
            for (String type : types) {
                query.setParameter("type" + count, "%" + type + "%");
                count++;
            }
        }
        query.setParameter("active", true);
        query.setMaxResults(maxResults);
        query.unwrap(SQLQuery.class).addScalar("id", LongType.INSTANCE).addScalar("code", StringType.INSTANCE)
                .addScalar("distance", DoubleType.INSTANCE);

        @SuppressWarnings("unchecked")
        List<Object[]> objects = query.getResultList();
        List<GeolocatedStore> stores = new ArrayList<GeolocatedStore>();
        for (java.lang.Object[] object : objects) {
            GeolocatedStore geolocatedStore = new GeolocatedStore();
            geolocatedStore.setId((Long) object[0]);
            geolocatedStore.setCode((String) object[1]);
            geolocatedStore.setDistance((Double) object[2]);
            stores.add(geolocatedStore);
        }
        return stores;
    }
    return null;
}

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

/**
 * ???/*  ww w .  j a  v a 2 s. co  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);
    }
}