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:com.sun.socialsite.business.impl.JPAMessageContentManagerImpl.java

/**
 * Note: using SuppressWarnings annotation because the JPA API is not genericized.
 *//*from  www. ja va  2  s  .  c  om*/
@SuppressWarnings(value = "unchecked")
public List<MessageContent> getUserMessages(Profile profile, int offset, int length)
        throws SocialSiteException {
    if (profile == null) {
        throw new SocialSiteException("profile is null");
    }
    Query query = strategy.getNamedQuery("MessageContent.getByProfile");
    if (offset != 0) {
        query.setFirstResult(offset);
    }
    if (length != -1) {
        query.setMaxResults(length);
    }
    query.setParameter(1, profile);
    return (List<MessageContent>) query.getResultList();
}

From source file:me.doshou.admin.monitor.web.controller.SQLExecutorController.java

@PageableDefaults(pageNumber = 0, value = 10)
@RequestMapping(value = "/sql", method = RequestMethod.POST)
public String executeQL(final @RequestParam("sql") String sql, final Model model, final Pageable pageable) {

    model.addAttribute("sessionFactory", HibernateUtils.getSessionFactory(em));

    String lowerCaseSQL = sql.trim().toLowerCase();
    final boolean isDML = lowerCaseSQL.startsWith("insert") || lowerCaseSQL.startsWith("update")
            || lowerCaseSQL.startsWith("delete");
    final boolean isDQL = lowerCaseSQL.startsWith("select");

    if (!isDML && !isDQL) {
        model.addAttribute(Constants.ERROR,
                "SQL????insert?update?delete?select");
        return showSQLForm();
    }// w  w  w .  jav a2 s  . co m
    try {
        new TransactionTemplate(transactionManager).execute(new TransactionCallback<Void>() {
            @Override
            public Void doInTransaction(TransactionStatus status) {

                if (isDML) {
                    Query query = em.createNativeQuery(sql);
                    int updateCount = query.executeUpdate();
                    model.addAttribute("updateCount", updateCount);
                } else {
                    String findSQL = sql;
                    String countSQL = "select count(*) count from (" + findSQL + ") o";
                    Query countQuery = em.createNativeQuery(countSQL);
                    Query findQuery = em.createNativeQuery(findSQL);
                    findQuery.setFirstResult(pageable.getOffset());
                    findQuery.setMaxResults(pageable.getPageSize());

                    Page page = new PageImpl(findQuery.getResultList(), pageable,
                            ((BigInteger) countQuery.getSingleResult()).longValue());

                    model.addAttribute("resultPage", page);

                    em.unwrap(Session.class).doWork(new Work() {
                        @Override
                        public void execute(final Connection connection) throws SQLException {
                            PreparedStatement psst = connection.prepareStatement(sql);
                            ResultSetMetaData metaData = psst.getMetaData();

                            List<String> columnNames = Lists.newArrayList();
                            for (int i = 1, l = metaData.getColumnCount(); i <= l; i++) {
                                columnNames.add(metaData.getColumnLabel(i));
                            }
                            psst.close();
                            model.addAttribute("columnNames", columnNames);
                        }
                    });
                }

                return null;
            }
        });
    } catch (Exception e) {
        StringWriter sw = new StringWriter();
        e.printStackTrace(new PrintWriter(sw));
        model.addAttribute(Constants.ERROR, sw.toString());
    }

    return showSQLForm();
}

From source file:eu.xipi.bro4xipi.brokermodel.BrokerJpaController.java

@SuppressWarnings("unchecked")
public List<Broker> read(int firstResult, int maxResults) {
    Query q = entityManager.createQuery("SELECT m FROM Broker m");
    q.setFirstResult(firstResult);
    q.setMaxResults(maxResults);//from   w w  w.j av a  2 s.  co m
    return q.getResultList();
}

From source file:com.fantasy.stataggregator.entities.dao.AbstractRepository.java

public List<T> findRange(int[] range) {
    javax.persistence.criteria.CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
    cq.select(cq.from(entityClass));//w  w  w  . j ava  2  s .  c  o  m
    javax.persistence.Query q = em.createQuery(cq);
    q.setMaxResults(range[1] - range[0] + 1);
    q.setFirstResult(range[0]);
    return q.getResultList();
}

From source file:org.syncope.core.persistence.dao.impl.TaskDAOImpl.java

@Override
public <T extends Task> List<T> findAll(final int page, final int itemsPerPage, final Class<T> reference) {

    final Query query = entityManager.createQuery(buildfindAllQuery(reference).toString());

    query.setFirstResult(itemsPerPage * (page <= 0 ? 0 : page - 1));

    if (itemsPerPage > 0) {
        query.setMaxResults(itemsPerPage);
    }//from  www  .  j a  va  2s  .c o  m

    return query.getResultList();
}

From source file:org.apache.cxf.fediz.service.idp.service.jpa.TrustedIdpDAOJPAImpl.java

@Override
public List<TrustedIdp> getTrustedIDPs(int start, int size) {
    List<TrustedIdp> list = new ArrayList<TrustedIdp>();

    Query query = null;
    query = em.createQuery("select t from TrustedIDP t");

    List<?> idpEntities = query.setFirstResult(start).setMaxResults(size).getResultList();

    for (Object obj : idpEntities) {
        TrustedIdpEntity entity = (TrustedIdpEntity) obj;
        list.add(entity2domain(entity));
    }/*from   w w w. j av  a2  s.co  m*/

    return list;
}

From source file:com.sun.socialsite.business.impl.JPAMessageContentManagerImpl.java

/**
 * Note: using SuppressWarnings annotation because the JPA API is not genericized.
 *///w w w.  j  a va2  s .  com
@SuppressWarnings(value = "unchecked")
public List<MessageContent> getUserMessages(Profile profile, String catlabel, int offset, int length)
        throws SocialSiteException {

    if (profile == null) {
        throw new SocialSiteException("profile is null");
    }
    Query query = strategy.getNamedQuery("MessageContent.getByProfileAndLabel");
    if (offset != 0) {
        query.setFirstResult(offset);
    }
    if (length != -1) {
        query.setMaxResults(length);
    }
    query.setParameter(1, profile);
    query.setParameter(2, catlabel);
    return (List<MessageContent>) query.getResultList();

}

From source file:be.fedict.eid.pkira.blm.model.contracts.ContractQuery.java

private void setPaging(Paging paging, Query query) {
    if (paging != null && paging.getFirstRow() != null && paging.getEndRow() != null)
        query.setFirstResult(paging.getFirstRow()).setMaxResults(paging.getEndRow() - paging.getFirstRow());
}

From source file:com.sun.socialsite.business.impl.JPAContentManagerImpl.java

/**
 * Note: using SuppressWarnings annotation because the JPA API is not genericized.
 *//*from  w  w  w .  j  a  va  2  s .c om*/
@SuppressWarnings(value = "unchecked")
public List<Content> getUserContent(Profile profile, int offset, int length) throws SocialSiteException {
    if (profile == null) {
        throw new SocialSiteException("profile is null");
    }

    Query query = strategy.getNamedQuery("Content.getByUserName");
    if (offset != 0) {
        query.setFirstResult(offset);
    }
    if (length != -1) {
        query.setMaxResults(length);
    }
    query.setParameter(1, profile);
    return (List<Content>) query.getResultList();
}

From source file:org.ejbca.core.ejb.audit.EjbcaAuditorSessionBean.java

@SuppressWarnings("unchecked")
@Override/*from  w  w w.  java2 s .c  o m*/
public List<? extends AuditLogEntry> selectAuditLog(final AuthenticationToken token, final String device,
        final int firstResult, final int maxResults, final String whereClause, final String orderClause,
        final List<Object> parameters) throws AuthorizationDeniedException {
    if (!IntegrityProtectedDevice.class.getSimpleName().equals(device)) {
        throw new UnsupportedOperationException(
                "selectAuditLog can only be used with " + IntegrityProtectedDevice.class.getSimpleName());
    }
    // Require that the caller is authorized to AUDITLOGSELECT just like in org.cesecore.audit.audit.SecurityEventsAuditorSessionBean.selectAuditLogs(...)
    assertAuthorization(token, AuditLogRules.VIEW.resource());
    // Assert that parameter is alphanumeric or one of ". ?<>!="
    assertLegalSqlString(whereClause, true);
    // Assert that parameter is alphanumeric or one of ". "
    assertLegalSqlString(orderClause, false);
    // Start building the query
    final StringBuilder queryBuilder = new StringBuilder("SELECT a FROM ")
            .append(AuditRecordData.class.getSimpleName()).append(" a");
    // Optionally add the WHERE clause
    if (whereClause != null && whereClause.length() > 0) {
        queryBuilder.append(" WHERE ").append(whereClause);
    }
    // Optionally add the ORDER clause
    if (orderClause != null && orderClause.length() > 0) {
        queryBuilder.append(" ORDER BY ").append(orderClause);
    }
    final String queryString = queryBuilder.toString();
    if (LOG.isDebugEnabled()) {
        LOG.debug("queryString: " + queryString);
    }
    final Query query = entityManager.createQuery(queryString);
    query.setFirstResult(firstResult);
    if (maxResults > 0) {
        query.setMaxResults(maxResults);
    }
    if (parameters != null) {
        for (int i = 0; i < parameters.size(); i++) {
            query.setParameter(i, parameters.get(i));
        }
    }

    //Prune out result pertaining to unauthorized CAs
    Set<Integer> authorizedCaIds = new HashSet<>(caSession.getAuthorizedCaIds(token));
    List<AuditLogEntry> resultList = new ArrayList<>();
    for (AuditLogEntry auditLogEntry : (List<AuditLogEntry>) query.getResultList()) {
        //The following values may leak CA Ids. 
        if (auditLogEntry.getModuleTypeValue().equals(ModuleTypes.CA)
                || auditLogEntry.getModuleTypeValue().equals(ModuleTypes.CERTIFICATE)
                || auditLogEntry.getModuleTypeValue().equals(ModuleTypes.CRL)) {
            if (!StringUtils.isEmpty(auditLogEntry.getCustomId())) {
                if (!authorizedCaIds.contains(Integer.valueOf(auditLogEntry.getCustomId()))) {
                    continue;
                }
            }
        }
        resultList.add(auditLogEntry);
    }
    return resultList;

}