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.maydesk.base.util.PDDataGridModel.java

License:Mozilla Public License

public void reloadData(int position) {
    dataList.clear();/*  w ww  .  java 2 s.  c om*/

    Criteria criteria = tableFactory.getCriteria(PDHibernateFactory.getSession());
    criteria.setProjection(Projections.countDistinct("id"));
    Long longRows = (Long) criteria.uniqueResult();
    totalRows = longRows.intValue();

    Projection projection = tableFactory.getProjectionList();
    if (projection == null) {
        criteria = tableFactory.getCriteria(PDHibernateFactory.getSession());
    } else {
        criteria.setProjection(projection);
    }
    criteria.setMaxResults(rowsPerPage);
    criteria.setFirstResult(position);
    tableFactory.addOrder(criteria);

    List list = criteria.list();
    for (Object o : list) {
        Object[] data = null;
        if (o instanceof Object[]) {
            data = (Object[]) o;
        } else {
            data = new Object[] { o }; // convert to array
        }
        dataList.add(tableFactory.createHeaderValue(data));
    }
}

From source file:com.medicfast.DAO.SenhaDAO.java

public Senha buscarUltimoAtendido(Usuario usuarioLogado) {
    Session session = (Session) em.getDelegate();
    Criteria c = session.createCriteria(Senha.class);
    c.add(Restrictions.eq("chamado", false));
    c.add(Restrictions.eq("pontoAtendimento", usuarioLogado.getPontoAtendimento()));
    c.setMaxResults(1);
    return (Senha) c.uniqueResult();
}

From source file:com.mercatis.lighthouse3.persistence.events.hibernate.EventRegistryImplementation.java

License:Apache License

/**
 * This method generates criteria for a given event template that also
 * contain an ordering clause on the date of occurrence.
 * //ww  w. j a va 2  s.c o m
 * @param session
 *            the Hibernate session to use for criteria generation
 * @param entityTemplate
 *            the template for which to generate the criteria
 * @param descending
 *            <code>true</code> if descending order is wanted (the default)
 *            or <code>false</code> for ascending order.
 * @return
 */
public Criteria generateOrderingCriteria(Session session, Event entityTemplate, boolean descending) {
    Criteria criteria = super.entityToCriteria(session, entityTemplate);

    if (entityTemplate.getContext() != null) {
        if (!Ranger.isEnumerationRange(entityTemplate.getContext()))
            criteria.add(Restrictions.eq("context", entityTemplate.getContext()));
        else
            criteria.add(Restrictions.in("context",
                    Ranger.castToEnumerationRange(entityTemplate.getContext()).getEnumeration()));

    }

    if (entityTemplate.getCode() != null) {
        if (!Ranger.isEnumerationRange(entityTemplate.getCode()))
            criteria.add(Restrictions.eq("code", entityTemplate.getCode()));
        else
            criteria.add(Restrictions.in("code",
                    Ranger.castToEnumerationRange(entityTemplate.getCode()).getEnumeration()));

    }

    if (entityTemplate.getLevel() != null) {
        if (!Ranger.isEnumerationRange(entityTemplate.getLevel()))
            criteria.add(Restrictions.eq("level", entityTemplate.getLevel()));
        else
            criteria.add(Restrictions.in("level",
                    Ranger.castToEnumerationRange(entityTemplate.getLevel()).getEnumeration()));
    }

    if (entityTemplate.getMachineOfOrigin() != null)
        criteria.add(Restrictions.eq("machineOfOrigin", entityTemplate.getMachineOfOrigin()));

    if (entityTemplate.getMessage() != null) {
        criteria.add(Restrictions.ilike("message", "%" + entityTemplate.getMessage() + "%"));
    }

    if (entityTemplate.getStackTrace() != null) {
        if (this.unitOfWork.getSqlDialect() instanceof org.hibernate.dialect.MySQL5InnoDBDialect)
            criteria.add(Restrictions.sqlRestriction("match ({alias}.STACK_TRACE) against (?)",
                    entityTemplate.getStackTrace(), StringType.INSTANCE));
        else
            criteria.add(Restrictions.ilike("stackTrace", "%" + entityTemplate.getStackTrace() + "%"));
    }

    if (entityTemplate.getDateOfOccurrence() != null) {
        if (!Ranger.isIntervalRange(entityTemplate.getDateOfOccurrence())) {
            criteria.add(Restrictions.eq("dateOfOccurrence", entityTemplate.getDateOfOccurrence()));
        } else {
            Date lowerBound = Ranger.castToIntervalRange(entityTemplate.getDateOfOccurrence()).getLowerBound();
            Date upperBound = Ranger.castToIntervalRange(entityTemplate.getDateOfOccurrence()).getUpperBound();

            if ((lowerBound == null) && (upperBound != null))
                criteria.add(Restrictions.le("dateOfOccurrence", upperBound));
            else if ((lowerBound != null) && (upperBound == null))
                criteria.add(Restrictions.ge("dateOfOccurrence", lowerBound));
            else if ((lowerBound != null) && (upperBound != null)) {
                criteria.add(Restrictions.le("dateOfOccurrence", upperBound));
                criteria.add(Restrictions.ge("dateOfOccurrence", lowerBound));
            }
        }
    }

    if (!entityTemplate.getTransactionIds().isEmpty()) {
        Set<Criterion> transactionRestrictions = new HashSet<Criterion>();
        for (String transactionId : entityTemplate.getTransactionIds())
            transactionRestrictions.add(Restrictions.sqlRestriction(
                    "exists (select lti.* from EVENT_TRANSACTION_IDS lti where {alias}.EVT_ID = lti.EVT_ID and lti.TRANSACTION_ID = ?)",
                    transactionId, StringType.INSTANCE));

        if (transactionRestrictions.size() == 1) {
            criteria.add(transactionRestrictions.iterator().next());
        } else {
            Iterator<Criterion> restrictions = transactionRestrictions.iterator();
            Criterion orCriterion = restrictions.next();

            while (restrictions.hasNext()) {
                orCriterion = Restrictions.or(orCriterion, restrictions.next());
            }

            criteria.add(orCriterion);
        }
    }

    for (String tag : entityTemplate.getTags())
        criteria.add(Restrictions.sqlRestriction(
                "exists (select lt.* from EVENT_TAGS lt where {alias}.EVT_ID = lt.EVT_ID and lt.TAG = ?)", tag,
                StringType.INSTANCE));

    for (String udf : entityTemplate.getUdfs().keySet()) {
        Object value = entityTemplate.getUdf(udf);

        if (udf.equals("eventRESTResourceLimitRestriction")) {
            criteria.setMaxResults((Integer) value);
            break;
        }

        String columnName = "";
        Type valueType = StringType.INSTANCE;

        if (value instanceof Boolean) {
            columnName = "BOOLEAN_VAL";
            valueType = BooleanType.INSTANCE;
        }

        if (value instanceof Integer) {
            columnName = "INTEGER_VAL";
            valueType = IntegerType.INSTANCE;
        }

        if (value instanceof Long) {
            columnName = "LONG_VAL";
            valueType = LongType.INSTANCE;
        }

        if (value instanceof Float) {
            columnName = "FLOAT_VAL";
            valueType = FloatType.INSTANCE;
        }

        if (value instanceof Double) {
            columnName = "DOUBLE_VAL";
            valueType = DoubleType.INSTANCE;
        }

        if (value instanceof Date) {
            columnName = "DATE_VAL";
            valueType = DateType.INSTANCE;
        }

        if (value instanceof byte[]) {
            columnName = "BINARY_VAL";
            valueType = BlobType.INSTANCE;
        }

        if (value instanceof String) {
            columnName = "STRING_VAL";
            valueType = StringType.INSTANCE;
        }

        criteria.add(Restrictions.sqlRestriction(
                "exists (select lu.* from EVENT_UDFS lu where {alias}.EVT_ID = lu.EVT_ID and lu.UDF = ? and lu."
                        + columnName + " = ?)",
                new Object[] { udf, value }, new Type[] { StringType.INSTANCE, valueType }));

    }

    if (descending)
        criteria.addOrder(Order.desc("dateOfOccurrence"));
    else
        criteria.addOrder(Order.asc("dateOfOccurrence"));

    return criteria;
}

From source file:com.miranteinfo.seam.framework.dao.DaoSupport.java

License:Open Source License

/**
 * Faz a pesquisa paginada com os parametros da paginacao obtidos da requisicao.
 * @param criteria/*from  w  w  w  . j a v a  2s  . c  o  m*/
 * @return lista
 */
protected List listPaged(Criteria criteria) {
    criteria.setFirstResult((Integer) Contexts.getEventContext().get(DAO_SUPPORT_FIRST_RESULT_PARAM));
    criteria.setMaxResults((Integer) Contexts.getEventContext().get(DAO_SUPPORT_MAX_RESULTS_PARAM));
    return criteria.list();
}

From source file:com.moviesdb.web.dao.BaseWebDao.java

@Override
public List paginatedSelect(Class clazz, int pageNumber, int pageSize) throws ApplicationException {
    List T = null;//  www  .  ja va  2  s  .  com
    try {
        Criteria criteria = getCurrentSession().createCriteria(clazz);
        criteria.setFirstResult((pageNumber) * pageSize);
        criteria.setMaxResults(pageSize);
        T = criteria.list();
    } catch (Exception e) {
        throw new ApplicationException("Paginated Select " + DAO_ERROR, e);
    }
    return T;
}

From source file:com.muslim.family.dao.impl.QuestionDAOImpl.java

public List<Question_tbl> getPaginatedQuestionsDao(int start, int length) {

    Criteria cr = sessionFactory.getCurrentSession().createCriteria(Question_tbl.class)
            .setProjection(Projections.projectionList().add(Projections.property("id"), "id")
                    .add(Projections.property("subject"), "Subject")
                    .add(Projections.property("views"), "Views"))
            .setResultTransformer(Transformers.aliasToBean(Question_tbl.class));
    cr.setFirstResult(start);/*  w  ww. ja v a2  s  .co  m*/
    cr.setMaxResults(length);

    return cr.list();

}

From source file:com.myapp.core.base.dao.impl.AbstractBaseDao.java

/**
 * ? ?? ?//  www .  j  a va  2  s.  c o  m
 * ? ???
 */

@Deprecated
public PageModel toPageDetachedCriteria(Class claz, DetachedCriteria dca, ProjectionList pList, Integer curPage,
        Integer pageSize) throws QueryException {
    Criteria query = dca.getExecutableCriteria(getCurrentSession());
    long rowCount = ((Long) query.setProjection(Projections.rowCount()).uniqueResult()).longValue();
    PageModel pm = new PageModel(curPage, pageSize, rowCount);
    if (pList != null) {
        query.setProjection(pList);
    } else {
        query.setProjection(null);
    }

    query.setResultTransformer(Transformers.aliasToBean(claz));
    query.setFirstResult(pm.getStartNum());
    query.setMaxResults(pageSize);
    pm.setDatas(query.list());
    return pm;
}

From source file:com.mycompany.thymeleafspringapp.dao.DealsDaoImpl.java

@Override
public Deals getDeal(long userId, long dealId) throws IllegalAccessException {
    Criteria crit = sessionFactory.openSession().createCriteria(Deals.class);
    crit.add(Restrictions.and(Restrictions.eq("dealId", dealId),
            Restrictions.eq("users", usersDAO.getUserById(userId))));
    crit.setMaxResults(1);
    List<Deals> deals = crit.list();
    if (deals.isEmpty()) {
        throw new IllegalAccessException("Unable to find the deal with given deal_id");

    }/*  ww  w  . j a  v a2  s . co m*/
    Deals d = deals.get(0);
    return d;
}

From source file:com.mycompany.thymeleafspringapp.dao.DealsDaoImpl.java

@Override
public byte[] getScreenshot(long userId, long imgId) {
    Criteria crit = sessionFactory.openSession().createCriteria(Screenshots.class);
    crit.add(Restrictions.eq("screenshotId", imgId));
    crit.setMaxResults(1);
    Screenshots s = (Screenshots) crit.list().get(0);
    return s.getDeals().getUsers().getUserId() == userId ? s.getFile() : null;
}

From source file:com.mycompany.thymeleafspringapp.dao.UsersDAOImpl.java

@Override
public Users getUserByName(String username) {
    Criteria crit = sessionFactory.openSession().createCriteria(Users.class);
    crit.add(Restrictions.or(Restrictions.eq("email", username), Restrictions.eq("username", username)));
    crit.setMaxResults(1);
    return (Users) crit.list().get(0);

}