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:org.compass.gps.device.jpa.indexer.DefaultJpaIndexEntitiesIndexer.java

public void performIndex(CompassSession session, IndexEntity[] entities) {
    for (IndexEntity indexEntity : entities) {
        EntityInformation entityInformation = (EntityInformation) indexEntity;
        if (jpaGpsDevice.isFilteredForIndex(entityInformation.getName())) {
            continue;
        }//ww  w  . ja  va 2s .co  m
        int fetchCount = jpaGpsDevice.getFetchCount();
        int current = 0;
        while (true) {
            if (!jpaGpsDevice.isRunning()) {
                return;
            }
            EntityManagerWrapper wrapper = jpaGpsDevice.getEntityManagerWrapper().newInstance();
            try {
                wrapper.open();
                EntityManager entityManager = wrapper.getEntityManager();
                if (log.isDebugEnabled()) {
                    log.debug(jpaGpsDevice.buildMessage("Indexing entities [" + entityInformation.getName()
                            + "] range [" + current + "-" + (current + fetchCount) + "] using query ["
                            + entityInformation.getQueryProvider() + "]"));
                }
                Query query = entityInformation.getQueryProvider().createQuery(entityManager,
                        entityInformation);
                query.setFirstResult(current);
                query.setMaxResults(fetchCount);
                List results = query.getResultList();
                for (Object result : results) {
                    session.create(result);
                }
                session.evictAll();
                entityManager.clear();
                wrapper.close();
                if (results.size() < fetchCount) {
                    break;
                }
                current += fetchCount;
            } catch (Exception e) {
                log.error(jpaGpsDevice.buildMessage("Failed to index the database"), e);
                wrapper.closeOnError();
                if (!(e instanceof JpaGpsDeviceException)) {
                    throw new JpaGpsDeviceException(jpaGpsDevice.buildMessage("Failed to index the database"),
                            e);
                }
                throw (JpaGpsDeviceException) e;
            }
        }
    }
}

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

/**
 * Note: using SuppressWarnings annotation because the JPA API is not genericized.
 *///from  ww  w . j  a v  a 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:org.syncope.core.persistence.dao.impl.ReportExecDAOImpl.java

private ReportExec findLatest(final Report report, final String field) {

    Query query = entityManager.createQuery("SELECT e " + "FROM " + ReportExec.class.getSimpleName() + " e "
            + "WHERE e.report=:report " + "ORDER BY e." + field + " DESC");
    query.setParameter("report", report);
    query.setMaxResults(1);

    List<ReportExec> result = query.getResultList();
    return result == null || result.isEmpty() ? null : result.iterator().next();
}

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

private <T extends Task> TaskExec findLatest(final T task, final String field) {

    Query query = entityManager.createQuery("SELECT e " + "FROM " + TaskExec.class.getSimpleName() + " e "
            + "WHERE e.task=:task " + "ORDER BY e." + field + " DESC");
    query.setParameter("task", task);
    query.setMaxResults(1);

    List<TaskExec> result = query.getResultList();
    return result == null || result.isEmpty() ? null : result.iterator().next();
}

From source file:gwap.game.quiz.QuizSessionBean.java

/**
 * Creates a new game array for the Quiz Game with 15 images
 *//* ww  w.j  a va2  s .  c  o  m*/
private boolean createWoelfflinResource() {

    this.questions = new ArrayList<QuizQuestionBean>(15);

    Query query = entityManager.createNamedQuery("artResource.woelfflin");
    query.setHint("org.hibernate.readOnly", true);
    query.setMaxResults(500);
    List<ArtResource> resultList = (List<ArtResource>) query.getResultList();

    int numImagesFound = 0;

    int listCounter = 0;
    for (ArtResource a : resultList) {
        listCounter++;
        String dateCreated = validateYear(a.getDateCreated());
        if (dateCreated != null) {
            String forename = a.getArtist().getForename();
            String surname = a.getArtist().getSurname();
            if (!(forename == null && surname == null)) {
                a.setDateCreated(dateCreated);
                QuizQuestionBean q = new QuizQuestionBean(numImagesFound, a);
                q.generateAnswers();
                questions.add(q);
                numImagesFound++;
                if (numImagesFound == 15) {
                    log.info("Found valid quiz game setup after observing " + listCounter + " ArtResources");
                    return true;

                }

            }
        }

    }
    log.error("Did not find 15 valid ArtResources out of 500 for a valid quiz game setup!");
    return false;

}

From source file:com.impetus.kundera.rest.common.EntityUtils.java

/**
 * @param queryString//from   ww  w  .  ja  va 2s . c  o m
 * @param q
 * @param em
 */
public static void setObjectQueryParameters(String queryString, String parameterString, Query q,
        EntityManager em, String mediaType) {
    MetamodelImpl metamodel = (MetamodelImpl) em.getEntityManagerFactory().getMetamodel();

    if (parameterString == null || parameterString.isEmpty()) {
        return;
    }

    Map<String, String> paramsMap = new HashMap<String, String>();
    ObjectMapper mapper = new ObjectMapper();

    try {
        paramsMap = mapper.readValue(parameterString, new TypeReference<HashMap<String, String>>() {
        });
        KunderaQuery kq = ((QueryImpl) q).getKunderaQuery();
        Set<Parameter<?>> parameters = kq.getParameters();
        for (String paramName : paramsMap.keySet()) {
            String value = paramsMap.get(paramName);

            if (paramName.equalsIgnoreCase("firstResult")) {
                q.setFirstResult(Integer.parseInt(value));

            } else if (paramName.equalsIgnoreCase("maxResult")) {
                q.setMaxResults(Integer.parseInt(value));

            } else if (StringUtils.isNumeric(paramName)) {
                for (Parameter param : parameters) {
                    if (param.getPosition() == Integer.parseInt(paramName)) {

                        Class<?> paramClass = param.getParameterType();
                        Object paramValue = null;
                        if (metamodel.isEmbeddable(paramClass)) {
                            paramValue = JAXBUtils.toObject(StreamUtils.toInputStream(value), paramClass,
                                    mediaType);

                        } else {
                            PropertyAccessor accessor = PropertyAccessorFactory.getPropertyAccessor(paramClass);
                            paramValue = accessor.fromString(paramClass, value);
                        }

                        q.setParameter(Integer.parseInt(paramName), paramValue);
                        break;
                    }
                }
            } else {
                for (Parameter param : parameters) {
                    if (param.getName().equals(paramName)) {

                        Class<?> paramClass = param.getParameterType();
                        Object paramValue = null;

                        if (metamodel.isEmbeddable(paramClass)) {
                            paramValue = JAXBUtils.toObject(StreamUtils.toInputStream(value), paramClass,
                                    mediaType);

                        } else {
                            PropertyAccessor accessor = PropertyAccessorFactory.getPropertyAccessor(paramClass);
                            paramValue = accessor.fromString(paramClass, value);
                        }
                        q.setParameter(paramName, paramValue);
                        break;
                    }
                }

            }
        }

    } catch (JsonParseException e) {
        log.error(e.getMessage());
    } catch (JsonMappingException e) {
        log.error(e.getMessage());
    } catch (IOException e) {
        log.error(e.getMessage());
    }
}

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

/**
 * Note: using SuppressWarnings annotation because the JPA API is not genericized.
 *///from   w w  w. ja va 2s  . c om
@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:org.oscarehr.common.dao.ConsultRequestDao.java

public List<Object[]> search(ConsultationRequestSearchFilter filter) {
    String sql = this.getSearchQuery(filter, false);
    MiscUtils.getLogger().info("sql=" + sql);
    Query query = entityManager.createQuery(sql);
    query.setFirstResult(filter.getStartIndex());
    query.setMaxResults(filter.getNumToReturn());
    return query.getResultList();
}

From source file:org.messic.server.datamodel.jpaimpl.DAOJPASong.java

@Override
@Transactional//w w  w .  jav a2  s.  c o m
public List<MDOSong> getAllOrderByLessPlayed(String username, int max) {
    Query query = entityManager.createQuery(
            "from MDOSong as a where (a.owner.login = :userName) ORDER BY (a.statistics.timesplayed) ASC");
    query.setMaxResults(max);
    query.setParameter("userName", username);

    @SuppressWarnings("unchecked")
    List<MDOSong> results = query.getResultList();

    query = entityManager
            .createQuery("from MDOSong as a where (a.statistics is null) AND (a.owner.login = :userName)");
    query.setParameter("userName", username);

    @SuppressWarnings("unchecked")
    List<MDOSong> otherResults = query.getResultList();

    otherResults.addAll(results);
    return otherResults;
}

From source file:com.mothsoft.alexis.dao.DataSetPointDaoImpl.java

@SuppressWarnings("unchecked")
@Override//  ww  w  .java2 s.c o  m
public DataSetPoint findLastPointBefore(final DataSet dataSet, final Timestamp timestamp) {
    final String queryString = "SELECT p FROM DataSetPoint p WHERE p.dataSet = :dataSet AND p.x <= :timestamp ORDER BY p.x DESC";
    final Query query = this.em.createQuery(queryString);
    query.setParameter("dataSet", dataSet);
    query.setParameter("timestamp", timestamp);
    query.setMaxResults(1);

    final List<DataSetPoint> points = query.getResultList();

    if (points.isEmpty()) {
        return null;
    } else {
        return points.get(0);
    }
}