Example usage for org.hibernate Criteria setFirstResult

List of usage examples for org.hibernate Criteria setFirstResult

Introduction

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

Prototype

public Criteria setFirstResult(int firstResult);

Source Link

Document

Set the first result to be retrieved.

Usage

From source file:com.lyh.licenseworkflow.dao.EnhancedHibernateDaoSupport.java

/**
 * ?/*from   www  .j  a  v  a2  s  .c om*/
 *
 * @param propertyNames ???
 * @param values        ???
 * @param start         ? - 0
 * @param pageSize      
 * @return
 */
@SuppressWarnings("unchecked")
public List<T> getPagingEntitiesByPropName(final String[] propertyNames, final Object[] values, final int start,
        final int pageSize) {
    if (ArrayUtils.isEmpty(propertyNames) || ArrayUtils.isEmpty(values)
            || propertyNames.length != values.length) {
        throw new IllegalArgumentException("Invalid arguments to execute sql query.");
    }
    return (List<T>) getHibernateTemplate().execute(new HibernateCallback() {
        public Object doInHibernate(Session session) throws HibernateException, SQLException {
            Criteria criteria = session.createCriteria(getEntityName());
            for (int i = 0; i < propertyNames.length; i++) {
                if (values[i] == null)
                    criteria.add(Restrictions.isNull(propertyNames[i]));
                else if (values[i].toString().indexOf("%") != -1) {// ,?value?%
                    criteria.add(Restrictions.like(propertyNames[i], values[i]));
                } else {
                    criteria.add(Restrictions.eq(propertyNames[i], values[i]));
                }
            }
            criteria.setFirstResult(start);
            criteria.setMaxResults(pageSize);
            return criteria.list();
        }
    });
}

From source file:com.lyh.licenseworkflow.dao.EnhancedHibernateDaoSupport.java

/**
 * ?SQLor?? from DeviceResource where (type = 'ROUTER' or type = 'L3_SWITCH');
 * <p/>/*w w  w.  jav  a 2  s .co m*/
 * <p/>
 * Notes: or<br>
 * <br>
 * Create Author : allen.wang <br>
 * Create Date : 2009-3-18
 *
 * @param start
 * @param pageSize
 * @param propertyName
 * @param values
 * @return
 */
@SuppressWarnings("unchecked")
public List<T> getPagingEntitiesByOrCondition(final int start, final int pageSize, final String propertyName,
        final Object... values) {
    return (List<T>) getHibernateTemplate().execute(new HibernateCallback() {
        public Object doInHibernate(Session session) throws HibernateException, SQLException {
            Criteria criteria = session.createCriteria(getEntityName());
            Disjunction d = Restrictions.disjunction();
            criteria = criteria.add(d);
            for (int i = 0; i < values.length; i++)
                d.add(Restrictions.eq(propertyName, values[i]));
            criteria.setFirstResult(start);
            criteria.setMaxResults(pageSize);
            return criteria.list();
        }
    });
}

From source file:com.lyh.licenseworkflow.dao.EnhancedHibernateDaoSupport.java

/**
 * ?? from DeviceResource where type = 'ROUTER' and temp = false;
 *
 * @param start         ?//from w  w  w .j a  v a2  s  .c o m
 * @param pageSize      ??
 * @param propertyNames ???
 * @param values        
 * @return ??
 */
@SuppressWarnings("unchecked")
public List<T> getPagingEntitiesByPropNames(final int start, final int pageSize, final String[] propertyNames,
        final Object[] values) {
    if (ArrayUtils.isEmpty(propertyNames) || ArrayUtils.isEmpty(values)
            || propertyNames.length != values.length) {
        throw new IllegalArgumentException("arguments is invalid.");
    }
    return (List<T>) getHibernateTemplate().execute(new HibernateCallback() {

        public Object doInHibernate(Session session) throws HibernateException, SQLException {
            Criteria c = session.createCriteria(getEntityName());
            c.setFirstResult(start);
            c.setMaxResults(pageSize);
            for (int i = 0; i < propertyNames.length; i++) {
                String propertyName = propertyNames[i];
                if (propertyName.indexOf(".") != -1) {
                    Criteria subC = null;
                    String[] props = StringUtils.split(propertyName, ".");
                    for (int j = 0; j < props.length; j++) {
                        if (j != props.length - 1) {
                            subC = c.createCriteria(props[j]);
                        }
                    }
                    if (values[i] == null)
                        subC.add(Restrictions.isNull(propertyName.substring(propertyName.indexOf(".") + 1)));
                    else
                        subC.add(Restrictions.eq(propertyName.substring(propertyName.indexOf(".") + 1),
                                values[i]));
                } else {
                    if (values[i] == null)
                        c.add(Restrictions.isNull(propertyNames[i]));
                    else if (values[i].toString().indexOf("%") != -1) {// ,?value?%
                        c.add(Restrictions.like(propertyNames[i], values[i]));
                    } else {
                        c.add(Restrictions.eq(propertyNames[i], values[i]));
                    }
                }
            }
            return c.list();
        }
    });
}

From source file:com.mac.green_leaves.v1.master.MasterRepository.java

public List<Model> list(String keyword, Integer pageNumber, Integer branch, Class modelClass) {
    Session session = getSession();//from ww w.j  av a 2  s .  c  o m

    Criteria criteria = session.createCriteria(modelClass);

    if (keyword != null) {
        Field[] fields = modelClass.getDeclaredFields();
        ArrayList<Criterion> criterions = new ArrayList<>();
        for (Field field : fields) {
            if (field.getType().isAssignableFrom(String.class)) {
                criterions.add(Restrictions.ilike(field.getName(), keyword, MatchMode.ANYWHERE));
            }
        }
        criteria.add(Restrictions.or(criterions.toArray(new Criterion[] {})));
    }

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

    if (pageNumber != null) {
        criteria.setFirstResult(PAGE_SIZE * (pageNumber - 1));
        criteria.setMaxResults(PAGE_SIZE);
    }

    return criteria.list();
}

From source file:com.marc.lastweek.business.entities.classifiedad.repository.ClassifiedAdRepository.java

License:Open Source License

@SuppressWarnings("unchecked")
public List<ClassifiedAd> basicSearch(FilterParameters parameters, Calendar from, int start, int count) {
    Criteria criteriaQuery = advancedSearchQueryConstructor(parameters, from);
    criteriaQuery.setFirstResult(start);
    criteriaQuery.setFetchSize(count);/*from w w w. j a  v a  2  s.  c om*/
    criteriaQuery.addOrder(Order.desc("publicationDate"));
    return criteriaQuery.list();
}

From source file:com.maydesk.base.util.PDDataGridModel.java

License:Mozilla Public License

public void reloadData(int position) {
    dataList.clear();/*from w w  w . j a  va  2 s  . co m*/

    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.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  av a 2 s  . com
 * @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.monits.commons.dao.GenericHibernateDao.java

License:Apache License

@SuppressWarnings("unchecked")
protected PaginatedResult<E> getPaginated(final Criteria criteria, final int page, final int amount)
        throws HibernateException, CloneNotSupportedException {

    Preconditions.checkArgument(page >= 0, "Invalid page " + page);
    Preconditions.checkArgument(amount > 0, "Invalid amount " + amount);

    final Session session = sessionFactory.getCurrentSession();

    final CloneableCriteria cc = new CloneableCriteria((CriteriaImpl) criteria);
    final CriteriaImpl clone = (CriteriaImpl) cc.clone().getExecutableCriteria(session);

    final Iterator<?> iterator = clone.iterateOrderings();
    while (iterator.hasNext()) {
        iterator.next();//from ww  w . j  a  v  a 2 s  .  com
        iterator.remove();
    }

    final long totalElements = getCount(clone);
    int pageNumber = page;
    if (pageNumber * amount >= totalElements) {
        pageNumber = (int) Math.ceil(totalElements / (double) amount) - 1;
    }

    criteria.setFirstResult(pageNumber * amount).setMaxResults(amount);

    return new PaginatedResult<E>(pageNumber + 1, criteria.list(), totalElements, amount);
}

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

@Override
public List paginatedSelect(Class clazz, int pageNumber, int pageSize) throws ApplicationException {
    List T = null;/*w  w w . java2  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);
    cr.setMaxResults(length);//w  ww.  ja v a  2s .co  m

    return cr.list();

}