Example usage for org.hibernate Criteria setMaxResults

List of usage examples for org.hibernate Criteria setMaxResults

Introduction

In this page you can find the example usage for org.hibernate Criteria setMaxResults.

Prototype

public Criteria setMaxResults(int maxResults);

Source Link

Document

Set a limit upon the number of objects to be retrieved.

Usage

From source file:com.hmsinc.epicenter.model.surveillance.impl.SurveillanceRepositoryImpl.java

License:Open Source License

public Anomaly getLatestAnomaly(final Geography geography, final Classification classification,
        final SurveillanceTask task, final SurveillanceMethod method, final SurveillanceSet set,
        final DateTime maxTime) {

    final Criteria c = criteriaQuery(entityManager, Anomaly.class);
    c.add(Restrictions.eq("geography", geography));
    if (classification != null) {
        c.add(Restrictions.eq("classification", classification));
    }/* w  w  w .j  a v a 2s .co  m*/

    if (task != null) {
        c.add(Restrictions.eq("task", task));
    }

    if (method != null) {
        c.add(Restrictions.eq("method", method));
    }

    if (set != null) {
        c.add(Restrictions.eq("set", set));
    }

    if (maxTime != null) {
        c.add(Restrictions.le("analysisTimestamp", maxTime));
    }

    c.setCacheable(false);
    c.addOrder(Order.desc("analysisTimestamp"));
    c.setMaxResults(1);

    final Anomaly anomaly = (Anomaly) c.uniqueResult();
    return anomaly;
}

From source file:com.hmsinc.epicenter.model.workflow.impl.WorkflowRepositoryImpl.java

License:Open Source License

@SuppressWarnings("unchecked")
public List<Investigation> getInvestigations(DateTime startDate, DateTime endDate, Geometry geometry,
        Collection<Organization> organizations, boolean showAll, Integer offset, Integer numRows) {

    final Criteria c = criteriaQuery(entityManager, Investigation.class, "investigation");
    applyInvestigationCriteria(c, startDate, endDate, geometry, organizations, showAll);

    if (offset != null) {
        c.setFirstResult(offset);/*from  w  w  w .  j  ava  2s  . c  om*/
    }

    if (numRows != null) {
        c.setMaxResults(numRows);
    }

    c.addOrder(Order.desc("timestamp"));

    return c.list();
}

From source file:com.hypersocket.repository.AbstractRepositoryImpl.java

License:Open Source License

@SuppressWarnings("unchecked")
@Transactional(readOnly = true)//from   w ww  . j a va  2s .com
public <T> List<T> search(Class<T> clz, final String searchColumn, final String searchPattern, final int start,
        final int length, final ColumnSort[] sorting, CriteriaConfiguration... configs) {
    Criteria criteria = createCriteria(clz);
    if (!StringUtils.isEmpty(searchPattern)) {
        criteria.add(Restrictions.ilike(searchColumn, searchPattern));
    }

    for (CriteriaConfiguration c : configs) {
        c.configure(criteria);
    }

    for (ColumnSort sort : sorting) {
        criteria.addOrder(sort.getSort() == Sort.ASC ? Order.asc(sort.getColumn().getColumnName())
                : Order.desc(sort.getColumn().getColumnName()));
    }

    criteria.setProjection(Projections.distinct(Projections.id()));

    criteria.setFirstResult(start);
    criteria.setMaxResults(length);

    List<T> ids = (List<T>) criteria.list();

    if (ids.isEmpty()) {
        return new ArrayList<T>();
    }

    criteria = createCriteria(clz);

    criteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
    criteria.add(Restrictions.in("id", ids));

    return ((List<T>) criteria.list());
}

From source file:com.hypersocket.resource.AbstractAssignableResourceRepositoryImpl.java

License:Open Source License

@SuppressWarnings("unchecked")
@Override// w w w  .  j  a  va2  s  .  co m
public Collection<T> searchAssignedResources(List<Principal> principals, final String searchPattern,
        final int start, final int length, final ColumnSort[] sorting, CriteriaConfiguration... configs) {

    Criteria criteria = createCriteria(getResourceClass());
    criteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);

    if (StringUtils.isNotBlank(searchPattern)) {
        criteria.add(Restrictions.ilike("name", searchPattern));
    }

    for (CriteriaConfiguration c : configs) {
        c.configure(criteria);
    }

    criteria.add(Restrictions.eq("realm", principals.get(0).getRealm()));
    criteria = criteria.createCriteria("roles");
    criteria.add(Restrictions.eq("allUsers", true));

    Set<T> everyone = new HashSet<T>(criteria.list());

    criteria = createCriteria(getResourceClass());

    ProjectionList projList = Projections.projectionList();
    projList.add(Projections.property("id"));
    projList.add(Projections.property("name"));

    criteria.setProjection(Projections.distinct(projList));
    criteria.setFirstResult(start);
    criteria.setMaxResults(length);

    if (StringUtils.isNotBlank(searchPattern)) {
        criteria.add(Restrictions.ilike("name", searchPattern));
    }

    for (CriteriaConfiguration c : configs) {
        c.configure(criteria);
    }

    for (ColumnSort sort : sorting) {
        criteria.addOrder(sort.getSort() == Sort.ASC ? Order.asc(sort.getColumn().getColumnName())
                : Order.desc(sort.getColumn().getColumnName()));
    }

    criteria.add(Restrictions.eq("realm", principals.get(0).getRealm()));

    criteria = criteria.createCriteria("roles");
    criteria.add(Restrictions.eq("allUsers", false));
    criteria = criteria.createCriteria("principals");

    List<Long> ids = new ArrayList<Long>();
    for (Principal p : principals) {
        ids.add(p.getId());
    }
    criteria.add(Restrictions.in("id", ids));

    List<Object[]> results = (List<Object[]>) criteria.list();

    if (results.size() > 0) {
        Long[] entityIds = new Long[results.size()];
        int idx = 0;
        for (Object[] obj : results) {
            entityIds[idx++] = (Long) obj[0];
        }

        criteria = createCriteria(getResourceClass());
        criteria.add(Restrictions.in("id", entityIds));

        everyone.addAll((List<T>) criteria.list());
    }
    return everyone;
}

From source file:com.hyzy.core.orm.hibernate.HibernateDao.java

License:Apache License

/**
 * ?Criteria,.//from www  .j  a  v a2  s  .  c o m
 */
protected Criteria setPageParameterToCriteria(final Criteria c, final Page<T> page) {

    //Assert.isTrue(page.getPageSize() > 0, "Page Size must larger than zero");

    if (page.getFirst() != -1 && page.getPageSize() != -1) {
        //hibernatefirstResult??0
        c.setFirstResult(page.getFirst() - 1);
        c.setMaxResults(page.getPageSize());
    }

    if (page.isOrderBySetted()) {
        String[] orderByArray = StringUtils.split(page.getOrderBy(), ',');
        String[] orderArray = StringUtils.split(page.getOrder(), ',');

        Assert.isTrue(orderByArray.length == orderArray.length,
                "???,????");

        for (int i = 0; i < orderByArray.length; i++) {
            if (Page.ASC.equals(orderArray[i])) {
                c.addOrder(Order.asc(orderByArray[i]));
            } else {
                c.addOrder(Order.desc(orderByArray[i]));
            }
        }
    }
    return c;
}

From source file:com.inet.base.ejb.business.BaseManageSessionBean.java

License:Open Source License

/**
 * Query and result the data from the given search persistence object.
 *
 * @param search the given persistence object used to build the criteria.
 * @param startAt the start at item the user want to retrieve.
 * @param maxItems the max items the user want to retrieve.
 *
 * @return the list of data that match the given criteria.
 *
 * @throws EjbException if we could not build and execute query to retrieve objects from the
 * container.//from   w  w w . j a v a  2  s  .  c om
 */
@SuppressWarnings({ "unchecked" })
public List<T> query(final T search, final int startAt, final int maxItems) throws EjbException {
    try {
        // create criteria from the given persistence object.
        final Criteria criteria = buildQuery(search);

        // set the limit objects that user want to retrieve.
        criteria.setFirstResult(startAt);
        criteria.setMaxResults(maxItems);

        return criteria.list();
    } catch (final HibernateException hbex) {
        final String msg = "Could not execute query to retrieve the objects from the container.";
        throw new EjbException(msg, hbex);
    }
}

From source file:com.inet.base.ejb.business.BaseSessionBean.java

License:Open Source License

/**
 * Query and result the data from the given search persistence object.
 *
 * @param search the given persistence object used to build the criteria.
 * @param startAt the start at item the user want to retrieve.
 * @param maxItems the max items the user want to retrieve.
 *
 * @return the list of data that match the given criteria.
 *
 * @throws EjbException if we could not execute query to retrieve the matching data in container.
 *///from  ww  w  . j a  v a  2  s.  c o  m
@SuppressWarnings({ "unchecked" })
@TransactionAttribute(TransactionAttributeType.SUPPORTS)
public List<T> query(final T search, final int startAt, final int maxItems) throws EjbException {
    try {
        // create criteria from the given persistence object.
        final Criteria criteria = buildQuery(search);

        // set the limit objects that user want to retrieve.
        criteria.setFirstResult(startAt);
        criteria.setMaxResults(maxItems);

        return criteria.list();
    } catch (final HibernateException hex) {
        final String msg = "Could not execute query to retrieve the matching data in container.";
        throw new EjbException(msg, hex);
    }
}

From source file:com.inet.mail.business.base.BaseMailBusinessBean.java

License:Open Source License

/**
 * Search and result the list of entity that match the given criteria.
 * /*from   w w  w.  j  a v a  2s .c o  m*/
 * @param search   T - the given criteria.
 * @param startAt    int - the given start item position.
 * @param maxItem   int - the given max items.
 * @return List<T> - list of entity.
 * @throws EjbException
 */
@SuppressWarnings("unchecked")
@TransactionAttribute(value = TransactionAttributeType.SUPPORTS)
public List<T> query(T search, int startAt, int maxItems) throws EJBException {
    // create criteria.
    Criteria criteria = buildQuery(search);

    // set start item position.
    criteria.setFirstResult(startAt);

    // set the expected max items.
    criteria.setMaxResults(maxItems);

    return criteria.list();
}

From source file:com.inet.mail.business.sr.MailHeaderSLBean.java

License:Open Source License

/**
 * {@inheritDoc}/*from  www.j av  a  2s  .com*/
 * 
 * @see com.inet.mail.business.sr.MailHeaderBase#search(com.inet.mail.data.SearchResultDTO)
 */
@TransactionAttribute(TransactionAttributeType.SUPPORTS)
public SearchResultDTO<MailHeader> search(SearchResultDTO<MailHeader> criteria) throws EJBException {
    // create the criteria.
    Criteria query = this.buildQuery(criteria.getCriteria());

    // the total result.
    int totalResult = criteria.getTotalResult();
    if (criteria.isCount()) {
        totalResult = count(criteria.getCriteria());
    }

    // set result information.
    query.setFirstResult(criteria.getStartPos());
    query.setMaxResults(criteria.getMaxResult());

    // get list of result.
    List<MailHeader> result = query(query);

    // create result.
    return new SearchResultDTO<MailHeader>(result, criteria.getStartPos(), criteria.getMaxResult(),
            totalResult);
}

From source file:com.inet.mail.business.sr.MailHeaderSLBean.java

License:Open Source License

/**
 * {@inheritDoc}//w  w w .ja  va 2  s .  c om
 * 
 * @see com.inet.mail.business.sr.MailHeaderBase#search(java.lang.String, int, int)
 */
@TransactionAttribute(TransactionAttributeType.SUPPORTS)
public SearchResultDTO<MailHeader> search(String criteria, int startAt, int maxItem) throws EJBException {
    // create the criteria.
    Criteria query = buildQuery(criteria);

    // get the total.
    int totalResult = count(criteria);

    // set result information.
    query.setFirstResult(startAt);
    query.setMaxResults(maxItem);

    // query data.
    List<MailHeader> result = query(query);

    // create result.
    return new SearchResultDTO<MailHeader>(result, startAt, maxItem, totalResult);
}