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:br.org.indt.ndg.server.survey.SurveyHandlerBean.java

public QueryInputOutputVO getAllImeisBySurvey(String surveyId, QueryInputOutputVO queryIOVO)
        throws MSMApplicationException {

    if (queryIOVO == null) {
        queryIOVO = new QueryInputOutputVO();
    }//from   w ww.  j  a  va  2  s  .  c om

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

    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 ((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();
    ArrayList<String> imeiIdListAux = new ArrayList<String>();

    while (it.hasNext()) {
        Transactionlog surveyTransactionLog = (Transactionlog) it.next();
        if (imeiIdListAux.contains(surveyTransactionLog.getImei().getImei())) {
            continue;
        }
        imeiIdListAux.add(surveyTransactionLog.getImei().getImei());

        Imei imei = null;
        if (surveyTransactionLog.getImei() != null) {
            imei = manager.find(Imei.class, surveyTransactionLog.getImei().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());
            }

            StringBuilder builder = new StringBuilder();
            builder.append("from Result where idSurvey = '");
            builder.append(surveyId);
            builder.append("' and imei = '");
            builder.append(vo.getImei());
            builder.append("'");
            Query query = manager.createQuery(builder.toString());

            vo.setQtdeResults(query.getResultList().size());
            ret.add(vo);
        }
    }

    queryIOVO.setRecordCount(ret.size());
    queryIOVO.setQueryResult(ret);

    return queryIOVO;
}

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

/**
 * Sql?// w  w  w .  j a va2s  . c o  m
 * @author ChenXiaolin 2015-12-1
 * @param paramVO 
 * @param sql
 * @return
 */
@SuppressWarnings("unchecked")
private List<TzQueryResponseProInfoVO> excuteSql(TzQueryRequestParamVO paramVO, String sql)
        throws DaoException {
    try {
        Query query = entityManager.createNativeQuery(sql);
        if (paramVO.getPage() > 0 && paramVO.getPageSize() > 0) {
            query.setFirstResult((paramVO.getPage() - 1) * paramVO.getPageSize());
            query.setMaxResults(paramVO.getPageSize());
        }
        List<Object[]> objects = query.getResultList();
        return setproQuery(objects);
    } catch (Exception e) {
        throw new DaoException(
                "TzQueryDaoImpl-->excuteSql()sql??????",
                e);
    }
}

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

/**
 * Get users of a website/*from   w ww .  j  a  va 2 s  . com*/
 */
public List getUsers(Weblog website, Boolean enabled, int offset, int length) throws WebloggerException {
    Query query = null;
    List results = null;
    boolean setRange = offset != 0 || length != -1;

    if (length == -1) {
        length = Integer.MAX_VALUE - offset;
    }

    if (enabled != null) {
        if (website != null) {
            query = strategy.getNamedQuery("User.getByEnabled&Permissions.website");
            query.setParameter(1, enabled);
            query.setParameter(2, website);
        } else {
            query = strategy.getNamedQuery("User.getByEnabled");
            query.setParameter(1, enabled);
        }
    } else {
        if (website != null) {
            query = strategy.getNamedQuery("User.getByPermissions.website");
            query.setParameter(1, website);
        } else {
            query = strategy.getNamedQuery("User.getAll");
        }
    }
    if (offset != 0) {
        query.setFirstResult(offset);
    }
    if (length != -1) {
        query.setMaxResults(length);
    }
    return query.getResultList();
}

From source file:io.isoft.blood.service.RdServiceImpl.java

@Override
public MyFilterResult findByFilter(MyPrintExportFilter filter) {

    try {/*w w  w  .ja  va2s .  c o m*/

        FilterBuilder filterBuilder = new FilterBuilder();

        String hql = " from BloodRdsMaster e ";
        if (filter.arguments.size() > 0)
            hql += " WHERE " + filterBuilder.buildHql(filter, "e");

        //???count?;
        //           org.hibernate.Query hquery = query.unwrap(org.hibernate.Query.class);
        Query countQuery = entityManager.createQuery("select count(*) " + hql);
        //we need to always have some sort for paging to work
        if (filter.sorts.size() == 0)
            hql += " ORDER BY e.autoId";
        else {
            //?;
            hql += " ORDER BY ";
            int sortIndex = 0;
            for (MyFilterSort myFilterSort : filter.sorts) {
                hql += String.format("  e.%s %s %s", myFilterSort.sortColumn,
                        myFilterSort.isAscending ? "" : "DESC",
                        (++sortIndex == filter.sorts.size()) ? "" : ",");
            }

        }
        //??
        Query query = entityManager.createQuery(hql);

        //?queryquery?
        for (ObjectParameter parameter : filterBuilder.parameters) {
            if (parameter.fieldName.equals("annualSalary")) {
                //blazeDs value?int?, ? big decimal
                parameter.value = new BigDecimal((Integer) parameter.value);
            }

            query.setParameter(parameter.name, parameter.value);
            countQuery.setParameter(parameter.name, parameter.value);
        }
        int recordCount = Integer.parseInt(countQuery.getSingleResult().toString());

        int pageStart = 0;
        int maxResult = 0;
        MyPrintExportOptions printExportOptions = filter.printExportOptions;
        String printExportOption = printExportOptions.getPrintExportOption();
        if (printExportOption.equals("All Pages")) {
            pageStart = 0;// options.getPageFrom() * options.getPageTo();
            maxResult = filter.pageCount * filter.pageSize;
        } else if (printExportOption.equals("Selected Pages")) {
            pageStart = (printExportOptions.getPageFrom() - 1) * filter.pageSize;
            maxResult = filter.pageSize
                    * (printExportOptions.getPageTo() - printExportOptions.getPageFrom() + 1);
        }
        List<BloodRdsMaster> results = query.setFirstResult(pageStart).setMaxResults(maxResult).getResultList();

        return new MyFilterResult((ArrayList<BloodRdsMaster>) results, recordCount);
    } catch (RuntimeException re) {
        throw re;
    }

}

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

/**
 * ??ID??/*from   w  w w  .j a va2s  .  c om*/
 * @author ChenXiaolin 2015-12-1
 * @param paramVO
 * @return
 * @throws DaoException
 */
@SuppressWarnings("unchecked")
@Override
public List<TzQueryResponseReportInfoVO> lookReport(TzQueryRequestParamVO paramVO) throws DaoException {
    try {
        StringBuffer sb = new StringBuffer();
        sb.append(
                " SELECT pro.name,pro.barcode,proInst.batch_serial_no,result.service_order,result.test_type,");
        sb.append("result.test_orgnization,IF(result.pass=1,'?','??') pass,result.fullPdfPath");
        sb.append(" FROM product_instance proInst");
        sb.append(" LEFT JOIN test_result result ON proInst.id = result.sample_id");
        sb.append(" LEFT JOIN product pro ON pro.id = proInst.product_id");
        sb.append(" WHERE result.del = 0 AND proInst.product_id = ").append(Long.parseLong(paramVO.getProId()));
        Query query = entityManager.createNativeQuery(sb.toString());
        if (paramVO.getPage() > 0 && paramVO.getPageSize() > 0) {
            query.setFirstResult((paramVO.getPage() - 1) * paramVO.getPageSize());
            query.setMaxResults(paramVO.getPageSize());
        }
        List<Object[]> objects = query.getResultList();
        return setLookReport(objects);
    } catch (Exception e) {
        throw new DaoException(
                "TzQueryDaoImpl-->lookReport()??ID??,?", e);
    }
}

From source file:io.isoft.reg.service.StaffDictServiceImpl.java

@Override
public MyFilterResult findByFilter(MyPrintExportFilter filter) {

    try {/*from ww w  .  j a va2s.  c o m*/

        FilterBuilder filterBuilder = new FilterBuilder();

        String hql = " from StaffDict e ";
        if (filter.arguments.size() > 0)
            hql += " WHERE " + filterBuilder.buildHql(filter, "e");

        //???count?;
        //           org.hibernate.Query hquery = query.unwrap(org.hibernate.Query.class);
        Query countQuery = entityManager.createQuery("select count(*) " + hql);
        //we need to always have some sort for paging to work
        if (filter.sorts.size() == 0)
            hql += " ORDER BY e.autoId";
        else {
            //?;
            hql += " ORDER BY ";
            int sortIndex = 0;
            for (MyFilterSort myFilterSort : filter.sorts) {
                hql += String.format("  e.%s %s %s", myFilterSort.sortColumn,
                        myFilterSort.isAscending ? "" : "DESC",
                        (++sortIndex == filter.sorts.size()) ? "" : ",");
            }

        }
        //??
        Query query = entityManager.createQuery(hql);

        //?queryquery?
        for (ObjectParameter parameter : filterBuilder.parameters) {
            if (parameter.fieldName.equals("annualSalary")) {
                //blazeDs value?int?, ? big decimal
                parameter.value = new BigDecimal((Integer) parameter.value);
            }

            query.setParameter(parameter.name, parameter.value);
            countQuery.setParameter(parameter.name, parameter.value);
        }
        int recordCount = Integer.parseInt(countQuery.getSingleResult().toString());

        int pageStart = 0;
        int maxResult = 0;
        MyPrintExportOptions printExportOptions = filter.printExportOptions;
        String printExportOption = printExportOptions.getPrintExportOption();
        if (printExportOption.equals("All Pages")) {
            pageStart = 0;// options.getPageFrom() * options.getPageTo();
            maxResult = filter.pageCount * filter.pageSize;
        } else if (printExportOption.equals("Selected Pages")) {
            pageStart = (printExportOptions.getPageFrom() - 1) * filter.pageSize;
            maxResult = filter.pageSize
                    * (printExportOptions.getPageTo() - printExportOptions.getPageFrom() + 1);
        }
        List<StaffDict> results = query.setFirstResult(pageStart).setMaxResults(maxResult).getResultList();

        return new MyFilterResult((ArrayList<StaffDict>) results, recordCount);
    } catch (RuntimeException re) {
        throw re;
    }

}

From source file:com.gettec.fsnip.fsn.dao.member.impl.MemberDAOImpl.java

/**
 * ??/*from w w  w .  j a  v a  2s.c  o m*/
 * @param page 
 * @param size 
 * @param organization 
 * @return
 * @throws DaoException 
 */
@SuppressWarnings("unchecked")
@Override
public List<Member> getAllLocalMember(int page, int size, Long organization) throws DaoException {
    try {
        String sql = "SELECT DISTINCT p.* FROM member p " + "Inner JOIN business_unit b ON p.producer_id=b.id "
                + "LEFT JOIN t_meta_initialize_member t ON p.id=t.member_id AND t.organization=?1 "
                + "WHERE b.organization=?2 AND t.first_storage_id is NULL ";

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

From source file:org.medici.bia.dao.JpaDao.java

/**
 * /*  w w  w.ja v a2  s  .  c om*/
 */
@Override
public Page searchMYSQL(org.medici.bia.common.search.Search searchContainer, PaginationFilter paginationFilter)
        throws PersistenceException {
    // We prepare object of return method.
    Page page = new Page(paginationFilter);

    Query query = null;
    // We set size of result.
    if (paginationFilter.getTotal() == null) {
        String countQuery = "SELECT COUNT(*) " + searchContainer.toJPAQuery();

        query = getEntityManager().createQuery(countQuery);
        page.setTotal(new Long((Long) query.getSingleResult()));
    }

    String objectsQuery = searchContainer.toJPAQuery();

    // We manage sorting (this manages sorting on multiple fields)
    paginationFilter = generatePaginationFilterMYSQL(paginationFilter);

    String jpql = objectsQuery + getOrderByQuery(paginationFilter.getSortingCriterias());
    logger.info("JPQL Query : " + jpql);
    query = getEntityManager().createQuery(jpql);
    // We set pagination  
    query.setFirstResult(paginationFilter.getFirstRecord());
    query.setMaxResults(paginationFilter.getLength());

    // We set search result on return method
    page.setList(query.getResultList());

    return page;
}

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

/**
 * ???????/* w  ww  .j  a va2  s .  co m*/
 * @author ChenXiaolin 2015-12-14
 * @param paramVO
 * @return
 * @throws DaoException
 */
@SuppressWarnings("unchecked")
@Override
public List<TzQueryResponseProListVO> getBusQueryProList(TzQueryRequestParamVO paramVO) throws DaoException {
    try {
        StringBuffer sb = new StringBuffer();
        sb.append(" SELECT * FROM ( ");
        sb.append(" SELECT pro.id id,pro.name proN,pro.barcode pb,pro.format f,pro.category cet");
        sb.append(" FROM tz_business_account account");
        sb.append(" INNER JOIN business_unit bus ON bus.id = account.out_business_id");
        sb.append(" INNER JOIN tz_business_account_info acInfo ON acInfo.business_account_id = account.id");
        sb.append(" INNER JOIN product pro ON pro.id = acInfo.product_id");
        sb.append(" WHERE bus.name = '").append(paramVO.getBusName()).append("'");

        if (StringUtil.isNotEmpty(paramVO.getLicenseNo())) {//??
            sb.append(" AND bus.license_no = '").append(paramVO.getLicenseNo()).append("'");
        }
        /* ?  */
        if (StringUtil.isNotEmpty(paramVO.getProName())) {//???
            sb.append(" AND pro.name LIKE '%").append(paramVO.getProName()).append("%'");
        }
        if (StringUtil.isNotEmpty(paramVO.getFormat())) {//?
            sb.append(" AND pro.format LIKE '%").append(paramVO.getFormat()).append("%'");
        }
        if (StringUtil.isNotEmpty(paramVO.getProBarcode())) {//???
            sb.append(" AND pro.barcode LIKE '%").append(paramVO.getProBarcode()).append("%'");
        }
        /* ?????? */
        //FSN??
        sb.append(" GROUP BY pro.id ) test");
        /* sql  */
        Query query = entityManager.createNativeQuery(sb.toString());
        if (paramVO.getPage() > 0 && paramVO.getPageSize() > 0) {
            query.setFirstResult((paramVO.getPage() - 1) * paramVO.getPageSize());
            query.setMaxResults(paramVO.getPageSize());
        }
        List<Object[]> objects = query.getResultList();
        return setBusQueryProList(objects);
    } catch (Exception e) {
        throw new DaoException(
                "TzQueryDaoImpl-->getBusQueryProList()???????,?",
                e);
    }
}

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

@Override
public QueryInputOutputVO listSurveysDB(NdgUser user, QueryInputOutputVO queryIOVO, Boolean isUploaded)
        throws MSMApplicationException, MSMSystemException {
    if (queryIOVO == null) {
        queryIOVO = new QueryInputOutputVO();
    }/*from  w ww.j av  a 2 s  .  co  m*/

    try {
        MSMBusinessDelegate msmBD = new MSMBusinessDelegate();

        String sqlCommand = "SELECT U FROM Survey U WHERE idUser LIKE "
                + msmBD.findNdgUserByName(user.getUserAdmin()).getIdUser();

        if (isUploaded) {
            sqlCommand += " AND upper(U.isUploaded) <> 'N' ";
        }

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

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

        Query q = manager.createQuery(sqlCommand);
        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> surveyList = new ArrayList<Object>();
        ArrayList<Survey> surveysListDB = (ArrayList<Survey>) q.getResultList();

        SurveyParser surveyParser = new SurveyParser();

        for (Survey survey : surveysListDB) {
            SurveyVO bean = new SurveyVO();

            SurveyXML surveyXml = surveyParser.parseSurvey(new StringBuffer(survey.getSurveyXml()), "UTF-8");

            /*
            surveyXml.setResults(loadResultsDB(surveyXml.getId()));
            */

            bean.setIdSurvey(surveyXml.getId());
            bean.setCheck("false");
            bean.setTitle(surveyXml.getTitle());
            bean.setResults(getQtResultsBySurvey(surveyXml.getId()));

            if ((survey.getIsUploaded() != 'n') && (survey.getIsUploaded() != 'N')) {
                bean.setIsUploaded('Y');
            } else {
                bean.setIsUploaded(survey.getIsUploaded());
            }

            if (!isUploaded) {
                bean.setSurvey(survey.getSurveyXml());
            }

            /*
            Collection<ImeiVO> devices = msmBD.getImeisSentBySurvey(surveyXml.getId());
            */

            Integer qtImeisSuccess = getQtImeisBySurvey(surveyXml.getId(), TransactionLogVO.STATUS_SUCCESS);
            bean.setDevice("" + qtImeisSuccess);

            /* 
            Collection<ImeiVO> pending = msmBD.getImeisUnsentBySurvey(surveyXml.getId());
            */

            Integer qtImeisPending = getQtImeisBySurvey(surveyXml.getId(), TransactionLogVO.STATUS_PENDING);
            bean.setPending("" + qtImeisPending);

            TransactionLogVO logs = msmBD.getSurveyReceived(surveyXml.getId());

            if (logs != null) {
                bean.setUser(logs.getUser());
                bean.setDate(SystemUtils.toDate(logs.getDtLog()));
            }

            surveyList.add(bean);

            log.info("Survey: " + surveyXml.getTitle());
        }

        queryIOVO.setQueryResult(surveyList);
    } catch (Exception e) {
        throw new SurveyNotParsedException();
    }

    return queryIOVO;
}