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:fr.natoine.dao.annotation.DAOAnnotation.java

/**
 * Retrieves a specified quantity of Annotations associated to a Resource specified by its URL
 * @param _url/*w w w.j  a va  2 s.  com*/
 * @param asc
 * @param first_indice
 * @param max_results
 * @return
 */
public List<Annotation> retrieveAnnotations(String _url, boolean asc, int first_indice, int max_results) {
    //EntityManagerFactory emf = this.setEMF();
    EntityManager em = emf.createEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {
        tx.begin();
        URI _uri = (URI) em.createQuery("from URI where effectiveURI = ?").setParameter(1, _url)
                .getSingleResult();
        if (_uri == null) {
            tx.commit();
            //   //em.close();
            System.out.println("[RetrieveAnnotation.retrieveAnnotations] unable to retrieve Annotations"
                    + " cause : there is no uri " + _url);
            return new ArrayList<Annotation>();
        }
        //List annotations = em.createQuery("select distinct annotation from Annotation as annotation inner join annotation.annotated as annotated inner join annotated.representsResource as uri where uri=?").setParameter(1, _uri).getResultList();
        String order_by_clause = " order by annotation.id desc";
        if (asc)
            order_by_clause = " order by annotation.id asc";
        Query _query = em.createQuery(
                "select distinct annotation from Annotation as annotation inner join annotation.annotatedURIs as uri where uri=?"
                        + order_by_clause)
                .setParameter(1, _uri);
        _query.setFirstResult(first_indice);
        _query.setMaxResults(max_results);
        List<Annotation> annotations = _query.getResultList();
        tx.commit();
        //em.close();
        return annotations;
    } catch (Exception e) {
        //tx.commit();
        tx.rollback();
        //em.close();
        System.out.println("[RetrieveAnnotation.retrieveAnnotations] unable to retrieve Annotations"
                + " cause : " + e.getMessage());
        return new ArrayList<Annotation>();
    }
}

From source file:portal.api.impl.PortalJpaController.java

@SuppressWarnings("unchecked")
public List<VxFMetadata> readVxFsMetadata(Long categoryid, int firstResult, int maxResults,
        boolean isPublished) {
    EntityManager entityManager = entityManagerFactory.createEntityManager();
    // Query q = entityManager.createQuery("SELECT m FROM VxFMetadata m");
    Query q;
    String s = "";

    if ((categoryid != null) && (categoryid >= 0)) {
        if (isPublished) {
            s = "a.published=TRUE";
        }//from ww  w.j a  v  a  2  s .c  o m
        q = entityManager.createQuery("SELECT a FROM VxFMetadata a WHERE " + s + " AND a.categories.id="
                + categoryid + " ORDER BY a.id");
    } else {
        if (isPublished) {
            s = "WHERE a.published=TRUE";
        }
        q = entityManager.createQuery("SELECT a FROM VxFMetadata a " + s + " ORDER BY a.id");
    }

    q.setFirstResult(firstResult);
    q.setMaxResults(maxResults);
    return q.getResultList();
}

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

/**
 * @inheritDoc//from   www  . ja  v  a  2 s . c om
 */
public List getComments(Weblog website, WeblogEntry entry, String searchString, Date startDate, Date endDate,
        String status, boolean reverseChrono, int offset, int length) throws WebloggerException {

    List params = new ArrayList();
    int size = 0;
    StringBuffer queryString = new StringBuffer();
    queryString.append("SELECT c FROM WeblogEntryComment c ");

    StringBuffer whereClause = new StringBuffer();
    if (entry != null) {
        params.add(size++, entry);
        whereClause.append("c.weblogEntry = ?").append(size);
    } else if (website != null) {
        params.add(size++, website);
        whereClause.append("c.weblogEntry.website = ?").append(size);
    }

    if (searchString != null) {
        params.add(size++, "%" + searchString + "%");
        appendConjuctionToWhereclause(whereClause, "(c.url LIKE ?").append(size).append(" OR c.content LIKE ?")
                .append(size).append(")");
    }

    if (startDate != null) {
        Timestamp start = new Timestamp(startDate.getTime());
        params.add(size++, start);
        appendConjuctionToWhereclause(whereClause, "c.postTime >= ?").append(size);
    }

    if (endDate != null) {
        Timestamp end = new Timestamp(endDate.getTime());
        params.add(size++, end);
        appendConjuctionToWhereclause(whereClause, "c.postTime <= ?").append(size);
    }

    if (status != null) {
        String comparisionOperator;
        if ("ALL_IGNORE_SPAM".equals(status)) {
            // we want all comments, except spam
            // so that means where status != SPAM
            status = WeblogEntryComment.SPAM;
            comparisionOperator = " <> ";
        } else {
            comparisionOperator = " = ";
        }
        params.add(size++, status);
        appendConjuctionToWhereclause(whereClause, "c.status ").append(comparisionOperator).append('?')
                .append(size);
    }

    if (whereClause.length() != 0) {
        queryString.append(" WHERE ").append(whereClause);
    }
    if (reverseChrono) {
        queryString.append(" ORDER BY c.postTime DESC");
    } else {
        queryString.append(" ORDER BY c.postTime ASC");
    }

    Query query = strategy.getDynamicQuery(queryString.toString());
    if (offset != 0) {
        query.setFirstResult(offset);
    }
    if (length != -1) {
        query.setMaxResults(length);
    }
    for (int i = 0; i < params.size(); i++) {
        query.setParameter(i + 1, params.get(i));
    }
    return query.getResultList();

}

From source file:portal.api.impl.PortalJpaController.java

public List<ExperimentMetadata> readExperimentsMetadata(Long categoryid, int firstResult, int maxResults,
        boolean isPublished) {
    EntityManager entityManager = entityManagerFactory.createEntityManager();
    Query q;
    String s = "";

    if ((categoryid != null) && (categoryid >= 0)) {
        if (isPublished) {
            s = "a.published=TRUE";
        }//from  w w w. j a  va  2 s  . com
        q = entityManager.createQuery("SELECT a FROM ExperimentMetadata a WHERE " + s + " AND a.categories.id="
                + categoryid + " ORDER BY a.id");
    } else {
        if (isPublished) {
            s = "WHERE a.published=TRUE";
        }
        q = entityManager.createQuery("SELECT a FROM ExperimentMetadata a " + s + " ORDER BY a.id");
    }

    q.setFirstResult(firstResult);
    q.setMaxResults(maxResults);
    return q.getResultList();
}

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

/**
 * {@inheritDoc}//from  w  ww.j a v a 2s .  com
 */
@Override
public Page searchDocumentsRelatedVolume(String volumeToSearch, PaginationFilter paginationFilter)
        throws PersistenceException {
    Page page = new Page(paginationFilter);

    Query query = null;
    String toSearch = new String(
            "FROM Document WHERE volume.summaryId=" + volumeToSearch + " 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 listSurveysByImeiDBWithoutResults(String imei, String status,
        QueryInputOutputVO queryIOVO) throws MSMApplicationException, MSMSystemException {
    if (queryIOVO == null) {
        queryIOVO = new QueryInputOutputVO();
    }/* www  .  j a  v  a 2s.c o m*/

    NdgUser user = businessDelegate.getUserByImei(imei);

    String sqlCommand = "from Transactionlog t where transactionType = " + "\'"
            + TransactionLogVO.TYPE_SEND_SURVEY + "\' " + "and imei.imei = :imei "
            + "and transactionStatus = :status ";

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

    sqlCommand += " group by t.survey.idSurvey ";

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

    Query q = manager.createQuery(sqlCommand);

    q.setParameter("imei", imei);
    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<Transactionlog> al = (ArrayList<Transactionlog>) q.getResultList();
    Iterator<Transactionlog> it = al.iterator();

    ArrayList<Object> surveyList = new ArrayList<Object>();

    while (it.hasNext()) {
        SurveyXML survey = null;
        Transactionlog surveyTransactionLog = (Transactionlog) it.next();
        SurveyVO vo = new SurveyVO();
        vo.setIdSurvey(surveyTransactionLog.getSurvey().getIdSurvey());

        survey = loadSurveyDB(user.getUserAdmin(), surveyTransactionLog.getSurvey().getIdSurvey());
        CreateXml.xmlToString(survey.getXmldoc());
        Survey surveyPojo = manager.find(Survey.class, surveyTransactionLog.getSurvey().getIdSurvey());

        try {
            byte[] stringXMLByte = surveyPojo.getSurveyXml().getBytes("UTF-8");
            vo.setSurvey(new String(stringXMLByte, "UTF-8"));

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        vo.setTitle(survey.getTitle());
        vo.setResultsSent(survey.getResultsSize());
        vo.setStatus(surveyTransactionLog.getTransactionStatus());

        surveyList.add(vo);
    }

    queryIOVO.setQueryResult(surveyList);

    return queryIOVO;
}

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

/**
 * ?id????/*  www .j a v  a 2s. c  om*/
 * @param paramVO
 * @param rId
 * @return
 * @throws DaoException
 */
@Override
public List<ProcurementUsageRecord> getProcurementUsageRecordList(TzQueryRequestParamVO paramVO, Long rId)
        throws DaoException {
    try {
        List<ProcurementUsageRecord> list = new ArrayList<ProcurementUsageRecord>();
        StringBuffer sql = new StringBuffer();
        sql.append("SELECT * FROM procurement_usage_record WHERE procurement_id=?1 ORDER BY use_date desc");
        Query query = entityManager.createNativeQuery(sql.toString(), ProcurementUsageRecord.class);
        query.setParameter(1, rId);
        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-->getProcurementUsageRecordList()?id?????",
                e);
    }
}

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

/**
 * {@inheritDoc}/*  ww w.j a va  2s .  com*/
 */
@Override
public Page searchSenderDocumentsPerson(String personToSearch, PaginationFilter paginationFilter)
        throws PersistenceException {
    Page page = new Page(paginationFilter);

    Query query = null;
    String toSearch = new String(
            "FROM Document WHERE senderPeople.personId=" + personToSearch + " 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.medici.bia.dao.document.DocumentDAOJpaImpl.java

/**
 * {@inheritDoc}/*from   w w  w . ja v  a 2  s .  c  o m*/
 */
@Override
public Page searchSenderDocumentsPlace(String placeToSearch, PaginationFilter paginationFilter)
        throws PersistenceException {
    Page page = new Page(paginationFilter);

    Query query = null;
    String toSearch = new String(
            "FROM Document WHERE senderPlace.placeAllId=" + placeToSearch + " 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:fr.natoine.dao.annotation.DAOAnnotation.java

/**
 * Retrieves a specified quantity of annotations associated to a Resource specified by its URL and ordered by AnnotationStatus
 * @param _url/*from www  .  j a  va  2  s .c  o m*/
 * @param asc
 * @param first_indice
 * @param max_results
 * @return
 */
public List<Annotation> retrieveAnnotationsGroupByStatus(String _url, boolean asc, int first_indice,
        int max_results) {
    //EntityManagerFactory emf = this.setEMF();
    EntityManager em = emf.createEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {
        tx.begin();
        URI _uri = (URI) em.createQuery("from URI where effectiveURI = ?").setParameter(1, _url)
                .getSingleResult();
        if (_uri == null) {
            tx.commit();
            //   //em.close();
            System.out.println("[RetrieveAnnotation.retrieveAnnotations] unable to retrieve Annotations"
                    + " cause : there is no uri " + _url);
            return new ArrayList<Annotation>();
        }
        //List annotations = em.createQuery("select distinct annotation from Annotation as annotation inner join annotation.annotated as annotated inner join annotated.representsResource as uri where uri=?").setParameter(1, _uri).getResultList();
        String order_by_clause = " annotation.id desc";
        if (asc)
            order_by_clause = " annotation.id asc";
        Query _query = em.createQuery(
                "select distinct annotation from Annotation as annotation inner join annotation.annotatedURIs as uri where uri=? order by annotation.status,"
                        + order_by_clause)
                .setParameter(1, _uri);
        _query.setFirstResult(first_indice);
        _query.setMaxResults(max_results);
        List<Annotation> annotations = _query.getResultList();
        //List annotations = em.createQuery("select distinct annotation from Annotation as annotation inner join annotation.annotatedURIs as uri where uri=? group by annotation.status" ).setParameter(1, _uri).getResultList();
        tx.commit();
        //em.close();
        return annotations;
    } catch (Exception e) {
        //tx.commit();
        tx.rollback();
        //em.close();
        System.out.println("[RetrieveAnnotation.retrieveAnnotations] unable to retrieve Annotations"
                + " cause : " + e.getMessage());
        return new ArrayList<Annotation>();
    }
}