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:org.j2free.jpa.Controller.java

/**
 *
 * @param <T>/*from   w  w w  . j av  a  2s.c  o m*/
 * @param query
 * @param start
 * @param limit
 * @param parameters
 * @return
 */
public <T> List<T> list(Query query, int start, int limit,
        KeyValuePair<String, ? extends Object>... parameters) {
    if (parameters != null) {
        for (KeyValuePair<String, ? extends Object> parameter : parameters) {
            query.setParameter(parameter.key, parameter.value);
        }
    }
    if (start > 0) {
        query.setFirstResult(start);
    }
    if (limit > 0) {
        query.setMaxResults(limit);
    }
    try {
        return (List<T>) query.getResultList();
    } catch (NoResultException nre) {
        return null;
    }
}

From source file:org.medici.bia.dao.user.UserDAOJpaImpl.java

@SuppressWarnings("serial")
@Override/*from   w  w w . j  a  v  a  2  s. c  o  m*/
public Page getUsersNotInCourse(Integer courseId, List<Authority> filteredAuthorities,
        PaginationFilter paginationFilter) throws PersistenceException {
    if (filteredAuthorities == null || filteredAuthorities.size() == 0) {
        filteredAuthorities = new ArrayList<Authority>() {
            {
                add(Authority.STUDENTS);
                add(Authority.TEACHERS);
            }
        };
    }

    Page page = new Page(paginationFilter);
    Query query = null;

    String jpql = "FROM UserRole AS userRole WHERE" + " userRole.userAuthority.authority IN (:authorities)"
            + " AND userRole.user NOT IN ("
            + "SELECT DISTINCT coursePeople.userRole.user FROM CoursePeople AS coursePeople WHERE"
            + " coursePeople.course.courseId = :courseId)";

    if (paginationFilter.getTotal() == null) {
        String countQuery = "SELECT COUNT(userRole.user) " + jpql;
        query = getEntityManager().createQuery(countQuery);
        query.setParameter("courseId", courseId);
        query.setParameter("authorities", filteredAuthorities);

        page.setTotal(new Long((Long) query.getSingleResult()));
        page.setTotalPages(PageUtils.calculeTotalPages(page.getTotal(), page.getElementsForPage()));
    } else {
        page.setTotal(paginationFilter.getTotal());
        page.setTotalPages(PageUtils.calculeTotalPages(paginationFilter.getTotal(),
                paginationFilter.getElementsForPage()));
    }

    query = getEntityManager().createQuery(
            "SELECT userRole.user " + jpql + getOrderByQuery(paginationFilter.getSortingCriterias()));
    query.setParameter("courseId", courseId);
    query.setParameter("authorities", filteredAuthorities);

    query.setFirstResult(PageUtils.calculeStart(page.getThisPage(), page.getElementsForPage()));
    query.setMaxResults(page.getElementsForPage());

    page.setList(query.getResultList());

    return page;
}

From source file:org.medici.bia.dao.userhistory.UserHistoryDAOJpaImpl.java

/**
 * {@inheritDoc}/*  w w w  .  j  a  v a 2 s  . c  om*/
 */
@Override
public Page findHistory(User user, Category category, PaginationFilter paginationFilter)
        throws PersistenceException {
    Page page = new Page(paginationFilter);

    if (paginationFilter.getTotal() == null) {
        String queryString = "SELECT count(user) FROM UserHistory WHERE user=:user and category=:category and logicalDelete=false ";

        Query query = getEntityManager().createQuery(queryString);
        query.setParameter("user", user);
        query.setParameter("category", category);
        page.setTotal(new Long((Long) query.getSingleResult()));
    }

    String objectsQuery = "FROM UserHistory WHERE user=:user and category=:category and logicalDelete=false ";

    paginationFilter = generatePaginationFilterMYSQL(category, paginationFilter);

    String jpql = objectsQuery + getOrderByQuery(paginationFilter.getSortingCriterias());
    logger.debug("JPQL Query : " + jpql);

    Query query = getEntityManager().createQuery(jpql);
    query.setParameter("user", user);
    query.setParameter("category", category);
    query.setFirstResult(paginationFilter.getFirstRecord());
    query.setMaxResults(paginationFilter.getLength());
    page.setList(query.getResultList());

    return page;
}

From source file:org.medici.bia.dao.userhistory.UserHistoryDAOJpaImpl.java

/**
 * {@inheritDoc}//from  w w  w.ja v a  2 s  .  com
 */
@Override
public Page findHistory(User user, Category category, PaginationFilter paginationFilter, Integer resultSize)
        throws PersistenceException {
    Page page = new Page(paginationFilter);

    if (paginationFilter.getTotal() == null) {
        String queryString = "SELECT count(user) FROM UserHistory WHERE user=:user and category=:category and logicalDelete=false ";

        Query query = getEntityManager().createQuery(queryString);
        query.setParameter("user", user);
        query.setParameter("category", category);
        // we need to force to resultSize total if result is bigger
        Long total = new Long((Long) query.getSingleResult());
        if (total > resultSize) {
            total = new Long(resultSize);
        }

        page.setTotal(total);
    }

    String queryString = "FROM UserHistory WHERE user=:user and category=:category and logicalDelete=false ORDER BY dateAndTime DESC";

    Query query = getEntityManager().createQuery(queryString);

    query.setParameter("user", user);
    query.setParameter("category", category);
    query.setFirstResult(paginationFilter.getFirstRecord());
    query.setMaxResults(page.getTotal().intValue());
    page.setList(query.getResultList());

    return page;
}

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

public List getUsers(Boolean enabled, Date startDate, Date endDate, int offset, int length)
        throws WebloggerException {
    Query query = null;
    List results = null;//from   w ww.ja v a 2  s  .c  om
    boolean setRange = offset != 0 || length != -1;

    if (endDate == null)
        endDate = new Date();

    if (enabled != null) {
        if (startDate != null) {
            Timestamp start = new Timestamp(startDate.getTime());
            Timestamp end = new Timestamp(endDate.getTime());
            query = strategy.getNamedQuery("User.getByEnabled&EndDate&StartDateOrderByStartDateDesc");
            query.setParameter(1, enabled);
            query.setParameter(2, end);
            query.setParameter(3, start);
        } else {
            Timestamp end = new Timestamp(endDate.getTime());
            query = strategy.getNamedQuery("User.getByEnabled&EndDateOrderByStartDateDesc");
            query.setParameter(1, enabled);
            query.setParameter(2, end);
        }
    } else {
        if (startDate != null) {
            Timestamp start = new Timestamp(startDate.getTime());
            Timestamp end = new Timestamp(endDate.getTime());
            query = strategy.getNamedQuery("User.getByEndDate&StartDateOrderByStartDateDesc");
            query.setParameter(1, end);
            query.setParameter(2, start);
        } else {
            Timestamp end = new Timestamp(endDate.getTime());
            query = strategy.getNamedQuery("User.getByEndDateOrderByStartDateDesc");
            query.setParameter(1, end);
        }
    }
    if (offset != 0) {
        query.setFirstResult(offset);
    }
    if (length != -1) {
        query.setMaxResults(length);
    }
    return query.getResultList();
}

From source file:org.votingsystem.web.accesscontrol.ejb.RepresentativeBean.java

private synchronized RepresentativeAccreditationsMetaInf getAccreditationsBackup(UserVS representative,
        Date selectedDate) throws IOException {
    log.info(format("representative: {0} - selectedDate: {1}", representative.getNif(), selectedDate));
    int pageSize = 100;
    int offset = 0;
    Query query = dao.getEM()
            .createQuery("select r from RepresentationDocument r where r.representative =:representative "
                    + "and r.dateCreated <:selectedDate and r.state in :inList and (r.dateCanceled is null or r.dateCanceled >:selectedDate)")
            .setParameter("representative", representative).setParameter("selectedDate", selectedDate)
            .setParameter("inList",
                    Arrays.asList(RepresentationDocument.State.CANCELED, RepresentationDocument.State.OK))
            .setMaxResults(pageSize);/*from  w  w w .  j  av a 2  s.  c o m*/

    String selectedDatePath = DateUtils.getDateStr(selectedDate, "yyyy/MM/dd");
    String accreditationsPath = format("/backup/AccreditationsBackup/{0}/representative{1}", selectedDatePath,
            representative.getNif());
    String downloadURL = config.getStaticResURL() + accreditationsPath + ".zip";
    String representativeURL = format("{0}/representative/id/{1}", config.getRestURL(), representative.getId());
    String basedir = config.getServerDir().getAbsolutePath() + accreditationsPath;
    new File(basedir).mkdirs();
    File zipResult = new File(basedir + ".zip");
    File metaInfFile;
    if (zipResult.exists()) {
        metaInfFile = new File(basedir + "/meta.inf");
        if (metaInfFile.exists()) {
            RepresentativeAccreditationsMetaInf metaInf = new ObjectMapper().readValue(metaInfFile,
                    new TypeReference<RepresentativeAccreditationsMetaInf>() {
                    });
            return metaInf;
        }
    }
    Long numAccreditations = 0L;
    List<RepresentationDocument> representationDocuments = null;
    while ((representationDocuments = query.setFirstResult(offset).getResultList()).size() > 0) {
        for (RepresentationDocument representationDocument : representationDocuments) {
            ++numAccreditations;
            MessageSMIME messageSMIME = representationDocument.getActivationSMIME();
            File smimeFile = new File(format("{0}/accreditation_{1}", basedir, representationDocument.getId()));
            IOUtils.write(messageSMIME.getContent(), new FileOutputStream(smimeFile));
            if ((numAccreditations % 100) == 0) {
                dao.getEM().flush();
                dao.getEM().clear();
                log.info("getAccreditationsBackup - processed representations: " + numAccreditations);
            }
        }
        offset = offset + pageSize;
    }
    RepresentativeAccreditationsMetaInf metaInf = new RepresentativeAccreditationsMetaInf(numAccreditations,
            selectedDate, representativeURL, accreditationsPath + ".zip", downloadURL);
    metaInfFile = new File(basedir + "/meta.inf");
    new ObjectMapper().writeValue(new FileOutputStream(metaInfFile), metaInf);
    new ZipUtils(basedir).zipIt(zipResult);
    log.info("getAccreditationsBackup - zipResult: " + zipResult.getAbsolutePath());
    return metaInf;
}

From source file:org.medici.bia.dao.image.ImageDAOJpaImpl.java

/**
 * {@inheritDoc}/*w ww .ja  va2 s .  co  m*/
 */
@Override
public Page getVolumeImages(PaginationFilter paginationFilter, Integer volNum, String volLetExt,
        String[] imageTitleFilters) throws PersistenceException {
    Page page = new Page(paginationFilter);

    String jpql = "FROM Image WHERE volNum = :volNum AND volLetExt "
            + (volLetExt != null ? "= :volLetExt" : "IS NULL");
    if (imageTitleFilters != null) {
        for (int i = 0; i < imageTitleFilters.length; i++) {
            jpql += " AND imageTitle LIKE '%" + imageTitleFilters[i] + "%'";
        }
    }

    Query query = null;

    if (paginationFilter.getTotal() == null) {
        String countQuery = "SELECT COUNT(*) " + jpql;
        query = getEntityManager().createQuery(countQuery);
        query.setParameter("volNum", volNum);
        if (volLetExt != null) {
            query.setParameter("volLetExt", volLetExt);
        }
        page.setTotal(new Long((Long) query.getSingleResult()));
        page.setTotalPages(PageUtils.calculeTotalPages(page.getTotal(), page.getElementsForPage()));
    } else {
        page.setTotal(paginationFilter.getTotal());
        page.setTotalPages(PageUtils.calculeTotalPages(paginationFilter.getTotal(),
                paginationFilter.getElementsForPage()));
    }

    query = getEntityManager().createQuery(jpql + getOrderByQuery(paginationFilter.getSortingCriterias()));
    query.setParameter("volNum", volNum);
    if (volLetExt != null) {
        query.setParameter("volLetExt", volLetExt);
    }

    query.setFirstResult(PageUtils.calculeStart(page.getThisPage(), page.getElementsForPage()));
    query.setMaxResults(paginationFilter.getLength());

    page.setList(query.getResultList());

    return page;
}

From source file:org.medici.bia.dao.user.UserDAOJpaImpl.java

/**
 * {@inheritDoc}/*ww  w  . java 2 s.c  o  m*/
 */
@Override
public Page findUsers(User user, Set<Authority> authorities, boolean searchAuthorities,
        PaginationFilter paginationFilter) {
    boolean authFilter = authorities != null && authorities.size() > 0;
    Page page = new Page(paginationFilter);
    Query query = null;
    String jpql = "FROM User ";
    String condition = getConditionOnUser(authFilter ? "user" : null, user);

    if (authFilter) {
        jpql += "AS user, UserRole AS role ";
    }

    if (!StringUtils.equals(condition, "")) {
        jpql = jpql + "WHERE " + condition;
    }

    if (authFilter) {
        if (!jpql.contains("WHERE")) {
            jpql += "WHERE ";
        } else {
            jpql += " AND ";
        }
        jpql += "user = role.user AND ";
        if (searchAuthorities) {
            jpql += "role.userAuthority.authority IN (:authorities)";
        } else {
            jpql += "NOT EXISTS (SELECT r FROM UserRole AS r WHERE r.user = user AND r.userAuthority.authority IN (:authorities))";
        }
    }

    if (paginationFilter.getTotal() == null) {
        String countQuery = (authFilter ? "SELECT COUNT(user) " : "SELECT COUNT(*) ") + jpql;
        query = getEntityManager().createQuery(countQuery);
        if (authFilter) {
            query.setParameter("authorities", authorities);
        }
        page.setTotal(new Long((Long) query.getSingleResult()));
    }

    paginationFilter = generatePaginationFilterMYSQL(paginationFilter);

    query = getEntityManager().createQuery((authFilter ? "SELECT DISTINCT user " : "") + jpql
            + getOrderByQuery(paginationFilter.getSortingCriterias()));

    if (authFilter) {
        query.setParameter("authorities", authorities);
    }

    query.setFirstResult(paginationFilter.getFirstRecord());
    query.setMaxResults(paginationFilter.getLength());

    page.setList(query.getResultList());

    return page;
}

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

public <T extends EntityBaseStandard, E extends AbstractFiltroJpa> List<T> findFilter(Class<T> classObj,
        E filtro) throws Exception {
    List<T> returnValue = null;

    EntityManagerFactory emf = null;/*from  ww w.j  av  a 2 s.  c o m*/
    EntityManager em = null;
    Iterator i = null;
    Query q = null;
    try {
        /* Istanzia l'entity manager */
        emf = getEntityManagerFactory();
        em = emf.createEntityManager();

        StringBuilder hqlQuery = new StringBuilder();

        hqlQuery.append("select t from " + classObj.getName() + " t ");

        hqlQuery.append(" WHERE ");
        if (filtro != null && StringUtils.isNotEmpty(filtro.getSQLWhere())) {
            hqlQuery.append(filtro.getSQLWhere());
        }

        if (filtro != null) {
            hqlQuery.append(filtro.getSQLSort());
        }

        /* Crea la query */
        logger.debug(hqlQuery.toString());
        q = em.createQuery(hqlQuery.toString());

        /*
         * Se il numero di elementi e' diverso da 0 specifico quanti e da
         * dove cominciare
         */
        if (filtro != null && filtro.getRighePerPagina() > 0) {
            q.setMaxResults(filtro.getRighePerPagina());
            if (filtro.getPagina() > 0) {
                q.setFirstResult((filtro.getPagina() - 1) * filtro.getRighePerPagina());

            }
        }

        if (filtro != null && filtro.getListaParametri() != null) {
            for (Entry<String, Object> parametro : filtro.getListaParametri().entrySet()) {
                q.setParameter(parametro.getKey(), parametro.getValue());
            }
        }

        /* Calcolo la collezione di elementi desiderati */
        returnValue = q.getResultList();

    } catch (Exception e) {
        throw e;
    } finally {
        if (!passedEm) {
            PersistenceManagerUtil.close(em);
        }
        em = null;
        q = null;
        i = null;
    }
    return returnValue;
}

From source file:io.apiman.manager.api.jpa.JpaStorage.java

/**
 * @see io.apiman.manager.api.core.IStorageQuery#getContracts(java.lang.String, java.lang.String, java.lang.String, int, int)
 *///from  w  w w  . j  ava  2  s .  co  m
@Override
public List<ContractSummaryBean> getContracts(String organizationId, String apiId, String version, int page,
        int pageSize) throws StorageException {
    int start = (page - 1) * pageSize;
    beginTx();
    try {
        EntityManager entityManager = getActiveEntityManager();
        String jpql = "SELECT c from ContractBean c " + "  JOIN c.api apiv " + "  JOIN apiv.api api "
                + "  JOIN c.client clientv " + "  JOIN clientv.client client " + "  JOIN api.organization sorg"
                + "  JOIN client.organization aorg" + " WHERE api.id = :apiId " + "   AND sorg.id = :orgId "
                + "   AND apiv.version = :version " + " ORDER BY sorg.id, api.id ASC";
        Query query = entityManager.createQuery(jpql);
        query.setParameter("orgId", organizationId);
        query.setParameter("apiId", apiId);
        query.setParameter("version", version);
        query.setFirstResult(start);
        query.setMaxResults(pageSize);
        List<ContractBean> contracts = query.getResultList();
        List<ContractSummaryBean> rval = new ArrayList<>(contracts.size());
        for (ContractBean contractBean : contracts) {
            ClientBean client = contractBean.getClient().getClient();
            ApiBean api = contractBean.getApi().getApi();
            PlanBean plan = contractBean.getPlan().getPlan();

            OrganizationBean clientOrg = entityManager.find(OrganizationBean.class,
                    client.getOrganization().getId());
            OrganizationBean apiOrg = entityManager.find(OrganizationBean.class, api.getOrganization().getId());

            ContractSummaryBean csb = new ContractSummaryBean();
            csb.setClientId(client.getId());
            csb.setClientOrganizationId(client.getOrganization().getId());
            csb.setClientOrganizationName(clientOrg.getName());
            csb.setClientName(client.getName());
            csb.setClientVersion(contractBean.getClient().getVersion());
            csb.setContractId(contractBean.getId());
            csb.setCreatedOn(contractBean.getCreatedOn());
            csb.setPlanId(plan.getId());
            csb.setPlanName(plan.getName());
            csb.setPlanVersion(contractBean.getPlan().getVersion());
            csb.setApiDescription(api.getDescription());
            csb.setApiId(api.getId());
            csb.setApiName(api.getName());
            csb.setApiOrganizationId(apiOrg.getId());
            csb.setApiOrganizationName(apiOrg.getName());
            csb.setApiVersion(contractBean.getApi().getVersion());

            rval.add(csb);
        }
        return rval;
    } catch (Throwable t) {
        logger.error(t.getMessage(), t);
        throw new StorageException(t);
    } finally {
        rollbackTx();
    }
}