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:com.panguso.lc.analysis.format.dao.impl.DaoImpl.java

@Override
public List<T> search(T condition, int pageNo, int pageSize) {
    StringBuilder qString = new StringBuilder("select model from " + entityClass.getSimpleName() + " model");
    StringBuilder qWhere = new StringBuilder(" where ");
    StringBuilder qCondition = new StringBuilder();
    PropertyDescriptor[] propertyDescriptors = PropertyUtils.getPropertyDescriptors(entityClass);
    for (int i = 0, count = propertyDescriptors.length; i < count; i++) {
        PropertyDescriptor propertyDescriptor = propertyDescriptors[i];
        String name = propertyDescriptor.getName();
        Class<?> type = propertyDescriptor.getPropertyType();
        String value = null;// w ww .j  a  v a2 s  .c  o m
        try {
            value = BeanUtils.getProperty(condition, name);
        } catch (Exception e) {
            // ?
            continue;
        }
        if (value == null || name.equals("class")) {
            continue;
        }
        if ("java.lang.String".equals(type.getName())) {
            qCondition.append("model.");
            qCondition.append(name);
            qCondition.append(" like ");
            qCondition.append("'%");
            qCondition.append(value);
            qCondition.append("%'");
        } else {
            qCondition.append("model.");
            qCondition.append(name);
            qCondition.append("=");
            qCondition.append(value);
        }
        qCondition.append(" and ");

    }
    if (qCondition.length() != 0) {
        qString.append(qWhere).append(qCondition);
        if (qCondition.toString().endsWith(" and ")) {
            qString.delete(qString.length() - " and ".length(), qString.length());
        }
    }
    Query query = em.createQuery(qString.toString());
    query.setFirstResult(pageNo * pageSize);
    query.setMaxResults(pageSize);
    return query.getResultList();
}

From source file:org.mitre.openid.connect.repository.impl.JpaEventRepository.java

@SuppressWarnings("unchecked")
@Override//from w ww .  ja  v a  2 s.c om
@Transactional
public Collection<Event> getEventsDuringPeriod(Date start, Date end, int startChunk, int chunkSize) {

    Query query = manager.createQuery("SELECT e FROM Event e WHERE e.timestamp BETWEEN :start AND :end");

    query = query.setParameter("start", start, TemporalType.DATE);
    query = query.setParameter("end", end, TemporalType.DATE);
    query = query.setFirstResult(startChunk);
    query = query.setMaxResults(chunkSize);

    return query.getResultList();
}

From source file:com.bizintelapps.bugtracker.dao.impl.GenericDaoImpl.java

private List<T> executeQueryReturnList(final String jpql, final PagingParams pagingParams,
        final Object... params) throws DataAccessException {
    Query query = entityManager.createQuery(jpql);
    if (pagingParams != null) {
        query.setFirstResult((int) pagingParams.getStart());
        query.setMaxResults(pagingParams.getMaxLimit());
    }//  w  w  w.  j a v  a 2 s .co  m
    int i = 1;
    for (Object param : params) {
        query.setParameter(i++, param);
    }
    try {
        List result = query.getResultList();
        return result;
    } catch (RuntimeException re) {
        log.debug(re);
        return null;
    }

}

From source file:org.broadleafcommerce.inventory.dao.InventoryDaoImpl.java

@SuppressWarnings("unchecked")
@Override//from  w  w  w  .j  a v a2 s  . c  o  m
public Inventory readInventoryForDefaultFulfillmentLocation(Sku sku) {
    Query query = em.createNamedQuery("BC_READ_SKU_INVENTORY_FOR_DEFAULT_LOCATION");
    query.setParameter("skuId", sku.getId());
    query.setMaxResults(1);
    List<Inventory> inventories = query.getResultList();
    if (CollectionUtils.isNotEmpty(inventories)) {
        return inventories.get(0);
    }
    return null;
}

From source file:gwap.rest.User.java

@GET
@Path("/highscore")
public Response getHighscore() {
    Query query = entityManager.createNamedQuery("highscore.all");
    query.setParameter("gametype", getGameType());
    query.setMaxResults(10);
    List<Highscore> highscoreList = query.getResultList();

    JSONArray highscoreListJSON = new JSONArray();
    for (int i = 0; i < highscoreList.size(); i++) {
        Highscore highscore = highscoreList.get(i);
        JSONObject highscoreJSON = new JSONObject();
        highscoreJSON.put("rank", i + 1);
        Person person = entityManager.find(Person.class, highscore.getPersonId());
        highscoreJSON.put("name", person.getExternalUsername());
        highscoreJSON.put("score", highscore.getScore());
        highscoreListJSON.add(highscoreJSON);
    }//  w  w w.  j  a  va2s  . c o  m

    return Response.ok(highscoreListJSON.toString(), MediaType.APPLICATION_JSON).build();
}

From source file:it.av.youeat.service.impl.DataRistoranteServiceHibernate.java

/**
 * {@inheritDoc}/*from w  ww.ja  v a2s.  c o  m*/
 */
@Override
public List<DataRistorante> freeTextSearch(String pattern, int maxResult) {
    FullTextEntityManager fullTextEntityManager = org.hibernate.search.jpa.Search
            .getFullTextEntityManager(getJpaTemplate().getEntityManager());
    String[] fields = new String[] { "name" };
    // TODO using dataristoranteanalyzer doesn't work
    // MultiFieldQueryParser parser = new MultiFieldQueryParser(fields, fullTextEntityManager.getSearchFactory()
    // .getAnalyzer("ristoranteanalyzer"));
    MultiFieldQueryParser parser = new MultiFieldQueryParser(Version.LUCENE_31, fields,
            new StandardAnalyzer(Version.LUCENE_31));
    org.apache.lucene.search.Query query;
    try {
        query = parser.parse(LuceneUtil.escapeSpecialChars(pattern));
    } catch (ParseException e) {
        throw new YoueatException(e);
    }
    javax.persistence.Query persistenceQuery = fullTextEntityManager.createFullTextQuery(query,
            DataRistorante.class);
    if (maxResult > 0) {
        persistenceQuery.setMaxResults(maxResult);
    }
    return persistenceQuery.getResultList();
}

From source file:edu.sabanciuniv.sentilab.sare.controllers.entitymanagers.LexiconBuilderController.java

/**
 * Gets a value indicating whether the provided token has been previously seen or not.
 * @param em the {@link EntityManager} to use.
 * @param builder the {@link LexiconBuilderDocumentStore} to use.
 * @param token the token to look for.// w w  w  . j a  v a 2 s.co  m
 * @return {@code true} if the token was seen; {@code false} otherwise.
 */
public boolean isSeenToken(EntityManager em, LexiconBuilderDocumentStore builder, String token) {
    Validate.notNull(em, CannedMessages.NULL_ARGUMENT, "em");
    Validate.notNull(builder, CannedMessages.NULL_ARGUMENT, "builder");

    Query query = em.createQuery(
            "SELECT doc FROM LexiconDocument doc " + "WHERE doc.store=:builder AND doc.title=:token");
    query.setMaxResults(1).setParameter("builder", builder).setParameter("token", token);

    return query.getResultList().size() > 0;
}

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

@Override
@Transactional/*from w w  w .ja va 2  s . c om*/
public List<MDOSong> getLovedSongs(String username, int max) {
    Query query = entityManager.createQuery(
            "from MDOSong as a where (a.owner.login = :userName) and (a.rate=2 or a.rate=3) ORDER BY (a.statistics.timesplayed) DESC");
    query.setParameter("userName", username);
    query.setMaxResults(max);

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

From source file:it.av.youeat.service.impl.DataRistoranteServiceHibernate.java

/**
 * {@inheritDoc}/*w  ww .  ja va  2 s .  c  o m*/
 */
@Override
@Transactional
public Collection<DataRistorante> getToBeImported(int maxResults) {
    Query query = getJpaTemplate().getEntityManager().createQuery(
            "select risto from DataRistorante as risto where imported = false and importfails = false order by random()");
    query.setMaxResults(maxResults);
    return query.getResultList();
}

From source file:it.av.youeat.service.impl.DataRistoranteServiceHibernate.java

@Override
public List<DataRistorante> freeTextSearch(String pattern, String city, String country, int maxResult) {
    FullTextEntityManager fullTextEntityManager = org.hibernate.search.jpa.Search
            .getFullTextEntityManager(getJpaTemplate().getEntityManager());
    StringBuffer searchPattern = new StringBuffer();
    // use the search pattern on the name, city and country are mandatory match
    if (StringUtils.isNotBlank(pattern)) {
        String patternClean = LuceneUtil.escapeSpecialChars(pattern);
        searchPattern.append(" name:(");
        patternClean = patternClean + "~";
        searchPattern.append(patternClean);
        searchPattern.append(") && ");
        searchPattern.append(" +city:(");
        searchPattern.append(city);/*ww w  . ja  va 2 s.c o m*/
        searchPattern.append(") && ");
        searchPattern.append(" +country:(");
        searchPattern.append(country);
        searchPattern.append(") ");
    }

    // TODO using dataristoranteanalyzer doesn't work
    // QueryParser queryParser = new QueryParser("", fullTextEntityManager.getSearchFactory().getAnalyzer(
    // "dataristoranteanalyzer"));
    QueryParser queryParser = new QueryParser(Version.LUCENE_31, "", new StandardAnalyzer(Version.LUCENE_31));

    org.apache.lucene.search.Query query;
    try {
        query = queryParser.parse(searchPattern.toString());
    } catch (Exception e) {
        throw new YoueatException(e);
    }
    javax.persistence.Query persistenceQuery = fullTextEntityManager.createFullTextQuery(query,
            DataRistorante.class);
    if (maxResult > 0) {
        persistenceQuery.setMaxResults(maxResult);
    }
    return persistenceQuery.getResultList();
}