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.jubinationre.model.dao.AdminDAOImpl.java

@Override
public Object readPropertyList(Object entity, String listType) {
    Admin admin = (Admin) entity;//from w  w w  . j  a v a2s  .  c  o m
    List list = null;
    switch (listType) {
    case "Inbox":
        try {
            session = getSessionFactory().openSession();
            session.beginTransaction();
            admin = (Admin) session.get(Admin.class, admin.getUsername());

            Criteria criteria = session.createCriteria(Message.class, "msg");
            criteria.add(Restrictions.eq("msg.receiver.username", admin.getUsername()));
            criteria.addOrder(Order.desc("messageId"));

            criteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
            criteria.setFirstResult(0);
            criteria.setMaxResults(10);
            list = criteria.list();
            session.getTransaction().commit();
        } catch (Exception e) {
            session.getTransaction().rollback();
            System.out.println("Error in reading Favourites at CustomerDAO " + e);
            e.printStackTrace();
            admin = null;
        } finally {
            if (session.isOpen()) {
                session.close();
            }

        }
        break;
    case "Sent":
        try {
            session = getSessionFactory().openSession();
            session.beginTransaction();

            admin = (Admin) session.get(Admin.class, admin.getUsername());

            Criteria criteria = session.createCriteria(Message.class, "msg");
            criteria.add(Restrictions.eq("msg.sender.username", admin.getUsername()));
            criteria.addOrder(Order.desc("messageId"));

            criteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
            criteria.setFirstResult(0);
            criteria.setMaxResults(10);
            list = criteria.list();
            session.getTransaction().commit();
        } catch (Exception e) {
            session.getTransaction().rollback();
            System.out.println("Error in reading Favourites at CustomerDAO " + e);
            e.printStackTrace();
            admin = null;
        } finally {
            if (session.isOpen()) {
                session.close();
            }
        }

        break;
    default:
        System.out.println("Not an option");
        admin = null;
        break;
    }

    return (T) list;
}

From source file:com.klistret.cmdb.dao.ElementDAOImpl.java

License:Open Source License

/**
 * Necessary to use the Projections to limit the selected columns to only
 * those defined to the Element tables (otherwise the returned columns
 * contains all columns for all associations).
 * //from w  ww.  j  a  v  a  2  s . com
 * @see com.klistret.cmdb.dao.ElementDAO.findByCriteria
 * @return Collection
 */
public List<Element> find(List<String> expressions, int start, int limit) {
    try {
        logger.debug("Finding elements by expression from start position [{}] with limit [{}] for session [{}]",
                new Object[] { start, limit, getSession().hashCode() });

        if (expressions == null)
            throw new ApplicationException("Expressions parameter is null", new IllegalArgumentException());

        Criteria criteria = new XPathCriteria(expressions, getSession()).getCriteria();

        criteria.setProjection(Projections.projectionList().add(Projections.property("id"))
                .add(Projections.property("type")).add(Projections.property("name"))
                .add(Projections.property("fromTimeStamp")).add(Projections.property("toTimeStamp"))
                .add(Projections.property("createId")).add(Projections.property("createTimeStamp"))
                .add(Projections.property("updateTimeStamp")).add(Projections.property("version"))
                .add(Projections.property("configuration")));

        criteria.addOrder(Order.asc("name"));

        criteria.setFirstResult(start);
        criteria.setFetchSize(limit);
        criteria.setMaxResults(limit);

        Object[] results = criteria.list().toArray();

        List<Element> elements = new ArrayList<Element>(results.length);
        logger.debug("Results length [{}]", results.length);

        for (int index = 0; index < results.length; index++) {
            Object[] row = (Object[]) results[index];

            Element element = new Element();
            element.setId((Long) row[0]);
            element.setType((ElementType) row[1]);
            element.setName((String) row[2]);
            element.setFromTimeStamp((Date) row[3]);
            element.setToTimeStamp((Date) row[4]);
            element.setCreateId((String) row[5]);
            element.setCreateTimeStamp((Date) row[6]);
            element.setUpdateTimeStamp((Date) row[7]);
            element.setVersion((Long) row[8]);
            element.setConfiguration((com.klistret.cmdb.ci.commons.Element) row[9]);

            elements.add(element);
        }

        results = null;

        return elements;
    } catch (StaleStateException e) {
        throw new ApplicationException("Element(s) found are stale which means newer version exists.");
    } catch (HibernateException e) {
        throw new InfrastructureException(e.getMessage(), e);
    }
}

From source file:com.klistret.cmdb.dao.RelationDAOImpl.java

License:Open Source License

/**
 * Finds relations based on XPath expressions
 * //  w ww  .j ava  2 s. c  om
 */
public List<Relation> find(List<String> expressions, int start, int limit) {
    try {
        logger.debug("Finding relations by expression from start position [{}] with limit [{}]", start, limit);

        if (expressions == null)
            throw new ApplicationException("Expressions parameter is null", new IllegalArgumentException());

        Criteria criteria = new XPathCriteria(expressions, getSession()).getCriteria();
        String alias = criteria.getAlias();

        criteria.setProjection(Projections.projectionList().add(Projections.property(alias + ".id"))
                .add(Projections.property(alias + ".type")).add(Projections.property(alias + ".source"))
                .add(Projections.property(alias + ".destination"))
                .add(Projections.property(alias + ".fromTimeStamp"))
                .add(Projections.property(alias + ".toTimeStamp"))
                .add(Projections.property(alias + ".createId"))
                .add(Projections.property(alias + ".createTimeStamp"))
                .add(Projections.property(alias + ".updateTimeStamp"))
                .add(Projections.property(alias + ".version"))
                .add(Projections.property(alias + ".configuration")));

        criteria.setFirstResult(start);
        criteria.setMaxResults(limit);
        criteria.setFetchSize(limit);

        Object[] results = criteria.list().toArray();

        List<Relation> relations = new ArrayList<Relation>(results.length);
        logger.debug("Results length [{}]", results.length);

        for (int index = 0; index < results.length; index++) {
            Object[] row = (Object[]) results[index];

            Relation relation = new Relation();
            relation.setId((Long) row[0]);
            relation.setType((RelationType) row[1]);
            relation.setSource((Element) row[2]);
            relation.setDestination((Element) row[3]);
            relation.setFromTimeStamp((Date) row[4]);
            relation.setToTimeStamp((Date) row[5]);
            relation.setCreateId((String) row[6]);
            relation.setCreateTimeStamp((Date) row[7]);
            relation.setUpdateTimeStamp((Date) row[8]);
            relation.setVersion((Long) row[9]);
            relation.setConfiguration((com.klistret.cmdb.ci.commons.Relation) row[10]);

            relations.add(relation);
        }

        results = null;

        return relations;
    } catch (StaleStateException e) {
        throw new ApplicationException(
                "Relation(s) found are stale which means newer version exists (Hibernate).");
    } catch (HibernateException e) {
        throw new InfrastructureException(e.getMessage(), e);
    }
}

From source file:com.krawler.crm.savedsearch.dao.SavedSearchDAOImpl.java

License:Open Source License

@Override
public List getSavedSearchQueries(String userid, int firstResult, int maxResults) throws ServiceException {
    List ll = null;//w  w  w . j a v a 2 s  .c om
    try {
        Criteria crit = getSavedSearchCriteria(userid);
        crit.setFirstResult(firstResult);
        crit.setMaxResults(maxResults);
        BuildCriteria.buildCriteria(BuildCriteria.OPERATORORDERDESC, BuildCriteria.ORDER, crit,
                Constants.updatedOn);
        ll = crit.list();
    } catch (Exception e) {
        throw ServiceException.FAILURE("RememberSearchDAOImpl.getSavedSearchQueries : " + e.getMessage(), e);
    }
    return ll;
}

From source file:com.kunckle.jetpower.core.base.repository.impl.BaseRepositorySupport.java

License:Apache License

/**
 * ?/*w w  w  .ja  va 2 s .c  o m*/
 *
 * @param searchAdapter ??
 * @return ?null
 * @throws IndexOutOfBoundsException
 */
@Override
@SuppressWarnings("unchecked")
public Page<E> findAll(SearchAdapter searchAdapter, PageAdapter pageAdapter) {
    pageAdapter.setCountOfElements(count(searchAdapter));
    if (pageAdapter.exists() && pageAdapter.getPageNumber() != 0) {
        throw new IndexOutOfBoundsException("?");
    } else if (pageAdapter.getCountOfElements() == 0) {
        return null;
    }

    if (searchAdapter.getPrepQL() != null) {
        Query query = getSession().createQuery("from " + entityClass.getSimpleName() + " "
                + searchAdapter.getPrepQL() + " " + pageAdapter.getPageSortAdapter().getPrepQL());
        query.setParameter(0, entityClass.getName());
        query.setFirstResult(pageAdapter.getPageOffset() * pageAdapter.getPageSize());
        query.setMaxResults(pageAdapter.getPageSize());
        return new Page<E>(pageAdapter, query.list());
    } else {
        Criteria criteria = searchAdapter.getCriteria(getSession().createCriteria(entityClass));
        criteria = pageAdapter.getPageSortAdapter().getCriteria(criteria);
        criteria.setFirstResult(pageAdapter.getPageOffset() * pageAdapter.getPageSize());
        criteria.setMaxResults(pageAdapter.getPageSize());
        return new Page<E>(pageAdapter, criteria.list());
    }
}

From source file:com.liferay.portal.workflow.jbpm.dao.CustomSession.java

License:Open Source License

protected void addPagination(Criteria criteria, int start, int end) {
    if ((start != QueryUtil.ALL_POS) && (end != QueryUtil.ALL_POS)) {
        criteria.setFirstResult(start);//w w w  . j  a  v  a 2 s  .  co m
        criteria.setMaxResults(end - start);
    }
}

From source file:com.liferay.portal.workflow.jbpm.dao.CustomSession.java

License:Open Source License

protected ProcessDefinition findProcessDefinition(String name) {
    try {// ww  w .j a  v  a 2 s .  com
        Criteria criteria = _session.createCriteria(ProcessDefinition.class);

        criteria.add(Restrictions.eq("name", name));

        Order order = Order.desc("version");

        criteria.addOrder(order);

        criteria.setFirstResult(0);
        criteria.setMaxResults(1);

        return (ProcessDefinition) criteria.uniqueResult();
    } catch (Exception e) {
        throw new JbpmException(e);
    }
}

From source file:com.lighting.platform.base.dao.HibernateDao.java

License:Apache License

/**
 * ?Criteria,./*from   ww w  .  jav a 2  s.com*/
 */
protected Criteria setPageParameterToCriteria(final Criteria c, final Page<T> page) {
    AssertUtils.isTrue(page.getPageSize() > 0, "Page Size must larger than zero");

    c.setFirstResult(page.getOffset());
    c.setMaxResults(page.getPageSize());

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

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

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

From source file:com.liusoft.dlog4j.dao.CommentDAO.java

License:Open Source License

/**
 * /*from  w w  w .  j  a  v a 2  s  .  c  om*/
 * @param eid
 * @param etype
 * @param fromIdx
 * @param fetchSize
 * @param reverse
 * @param withContent
 * @return
 */
public static List listComments(int otype, int oid, int eid, int etype, int fromIdx, int fetchSize,
        boolean reverse, boolean withContent) {
    Session ssn = getSession();
    Criteria crit = ssn.createCriteria(withContent ? CommentBean.class : CommentOutlineBean.class);
    crit.add(Expression.eq("ownerType", otype));
    crit.add(Expression.eq("ownerIdent", oid));
    if (eid > 0)
        crit.add(Expression.eq("eid", eid));
    if (etype >= 0)
        crit.add(Expression.eq("etype", etype));
    crit.addOrder(reverse ? Order.desc("id") : Order.asc("id"));
    if (fromIdx > 0)
        crit.setFirstResult(fromIdx);
    if (fetchSize > 0)
        crit.setMaxResults(fetchSize);
    return crit.list();
}

From source file:com.lm.lic.manager.hibernate.LicenseDAO.java

License:Open Source License

@SuppressWarnings("unchecked")
public List<License> findInUseIsvProdLicenses(String isvId, String prodId, String prodDefId, String storeId,
        String platformId, Integer firstResult, Integer maxResults, String orderBy, String orderDir,
        Date startDate, Date endDate) {
    List<License> licenses = null;
    try {//from w w  w  . ja v a2s .c  o m
        Criteria mainCriteria = getSession().createCriteria(License.class);

        ProductInstanceCriterias prodInstCriterias = addIsvProductInstProductDefStorePlatfrmCriteria(isvId,
                prodId, prodDefId, storeId, platformId, mainCriteria);

        addDateRangeRestrictions(TIME_ACTIVATED, startDate, endDate, mainCriteria);

        mainCriteria.add(Restrictions.eq("inUse", true));
        mainCriteria.add(Restrictions.eq("decom", false));

        mainCriteria.setFirstResult(firstResult);
        mainCriteria.setMaxResults(maxResults);

        addOrderByToCriteria(orderBy, orderDir, mainCriteria, prodInstCriterias);

        licenses = mainCriteria.list();

    } catch (RuntimeException re) {
        log.error("find by property name failed", re);
        throw re;
    }
    return licenses;
}