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.jdon.persistence.hibernate.HibernateTemplate.java

License:Apache License

public List findByCriteria(final DetachedCriteria criteria, final int firstResult, final int maxResults)
        throws Exception {

    return (List) doHibernate(new HibernateCallback() {
        public Object execute(Session session) throws HibernateException {
            Criteria executableCriteria = criteria.getExecutableCriteria(session);
            prepareCriteria(executableCriteria);
            if (firstResult >= 0) {
                executableCriteria.setFirstResult(firstResult);
            }/*w  ww  .  j  a  v a  2  s. c  om*/
            if (maxResults > 0) {
                executableCriteria.setMaxResults(maxResults);
            }
            return executableCriteria.list();
        }
    });
}

From source file:com.jdon.persistence.hibernate.HibernateTemplate.java

License:Apache License

public List findByExample(final Object exampleEntity, final int firstResult, final int maxResults)
        throws Exception {

    return (List) doHibernate(new HibernateCallback() {
        public Object execute(Session session) throws HibernateException {
            Criteria executableCriteria = session.createCriteria(exampleEntity.getClass());
            executableCriteria.add(Example.create(exampleEntity));
            prepareCriteria(executableCriteria);
            if (firstResult >= 0) {
                executableCriteria.setFirstResult(firstResult);
            }/*from   w  ww  .j  a  va  2s  .  co m*/
            if (maxResults > 0) {
                executableCriteria.setMaxResults(maxResults);
            }
            return executableCriteria.list();
        }
    });
}

From source file:com.jeroensteenbeeke.hyperion.data.HibernateDAO.java

License:Open Source License

@Override
public List<T> findByFilter(SearchFilter<T> filter, long offset, long count) {
    Criteria crit = applyOrderBy(createCriteria(filter), filter);

    if (crit != null) {
        crit.setMaxResults((int) count);
        crit.setFirstResult((int) offset);

        return crit.list();
    }/* ww w.  j a  v  a 2s  .c o m*/

    return new LinkedList<T>();
}

From source file:com.jeysan.modules.orm.hibernate.HibernateDao.java

License:Apache License

/**
 * ?Criteria,.//from   w w w .j  a  v  a 2 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");

    //hibernatefirstResult??0
    if (page.getPageSize() != -1) {
        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,
                "???,????");

        return HibernateUtils.checkCriteria4SubOrder(c, orderArray, orderByArray);
    }
    //logger.debug("c:::"+c);
    return c;
}

From source file:com.jfootball.dao.hibernate.PlayerDaoImpl.java

License:Open Source License

/**
 * Method to get a player/*from   ww  w.ja  v  a 2 s.c o m*/
 * 
 * @param playerId
 *            the playerId id
 * @return the players found
 */
public HashMap<String, Object> getNextId(Long teamId, Integer counter) {
    logger.info("Next id team " + teamId + " counter " + counter);

    HashMap<String, Object> map = new HashMap<String, Object>();

    Session session = hibernateTemplate.getSessionFactory().getCurrentSession();
    Criteria criteria = session.createCriteria(Player.class);
    criteria.add(Restrictions.eq("team.id", teamId));
    criteria.addOrder(Order.asc("position"));
    criteria.addOrder(Order.asc("number"));
    criteria.addOrder(Order.asc("dateOfBirth"));

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

    Long nextId = 0L;
    Player player = null;

    if (criteria.uniqueResult() != null) {
        player = (Player) criteria.uniqueResult();
        nextId = player.getId();

        map.put("counter", counter);
        map.put("id", nextId);
        map.put("player", player.getFirstName() + " " + player.getLastName());
    } else {
        nextId = -1L;

        map.put("counter", counter);
        map.put("id", -1L);
        map.put("player", null);
    }

    logger.info("Next id returned");

    return map;
}

From source file:com.jfootball.dao.hibernate.PlayerDaoImpl.java

License:Open Source License

/**
 * Method to get a player/*from   ww  w .ja v  a  2 s.  c o  m*/
 * 
 * @param playerId
 *            the playerId id
 * @return the players found
 */
public HashMap<String, Object> getPrevId(Long teamId, Integer counter) {
    logger.info("Prev id team " + teamId + " counter " + counter);

    HashMap<String, Object> map = new HashMap<String, Object>();

    Session session = hibernateTemplate.getSessionFactory().getCurrentSession();
    Criteria criteria = session.createCriteria(Player.class);
    criteria.add(Restrictions.eq("team.id", teamId));
    criteria.addOrder(Order.desc("position"));
    criteria.addOrder(Order.desc("number"));
    criteria.addOrder(Order.desc("dateOfBirth"));

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

    Long prevId = 0L;
    Player player = null;

    if (criteria.uniqueResult() != null) {
        player = (Player) criteria.uniqueResult();
        prevId = player.getId();

        map.put("counter", counter);
    } else {
        map.put("counter", -1);
    }

    map.put("id", prevId);
    map.put("player", player.getFirstName() + " " + player.getLastName());

    logger.info("Prev id returned");

    return map;
}

From source file:com.jscompany.ebsystem.lazymodels.BaseLazyDataModel.java

public void criteriaPageSetup(Criteria crit, int first, int pageSize) {
    try {//ww  w. j  a v a 2  s  . c  o m
        crit.setFirstResult(first);
        crit.setMaxResults(pageSize);
    } catch (Exception e) {
        Logger.getLogger(BaseLazyDataModel.class.getName()).log(Level.SEVERE, null, e);
    }
}

From source file:com.jubination.model.dao.AdminDAOImpl.java

@Transactional(propagation = Propagation.REQUIRED, readOnly = true)
public Object readPropertyList(Object entity, String listType) {
    Admin admin = (Admin) entity;//from  ww w . ja  v  a  2s.  co  m
    List list = null;
    switch (listType) {
    case "Inbox":
        session = getSessionFactory().getCurrentSession();

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

        Criteria criteria = session.createCriteria(MailMessage.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();

        break;
    case "Sent":
        session = getSessionFactory().getCurrentSession();

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

        criteria = session.createCriteria(MailMessage.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();

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

    return (T) list;
}

From source file:com.jubinationre.model.dao.AdminDAOImpl.java

@Override
public Object readPropertyList(Object entity, String listType) {
    Admin admin = (Admin) entity;/*w w  w .  j a v  a  2s .co  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  w  w .j  a v  a  2  s. co  m*/
 * @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);
    }
}