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:br.ufac.sion.dao.InscricaoFacade.java

@Override
public List<Inscricao> findByCargoAndLocalidade(FiltroInscritosRelatorio filtroRelatorio) {
    Session session = em.unwrap(Session.class);
    Criteria criteria = session.createCriteria(Inscricao.class);

    criteria.createAlias("cargoConcurso", "cc")
            .add(Restrictions.eq("cc.concurso", filtroRelatorio.getConcurso()));
    criteria.createAlias("candidato", "c");

    if (filtroRelatorio.getCargo() != null && filtroRelatorio.getCargo().getId() != null) {
        criteria.add(Restrictions.eq("cargoConcurso", filtroRelatorio.getCargo()));
    }// ww  w .  jav a2s .  c o  m

    criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);

    criteria.setFirstResult(filtroRelatorio.getPrimeiroRegistro());
    criteria.setMaxResults(filtroRelatorio.getQuantidadeRegistros());

    Criterion confirmada = Restrictions.eq("status", SituacaoInscricao.CONFIRMADA);
    Criterion judice = Restrictions.eq("status", SituacaoInscricao.SUB_JUDICE);
    criteria.add(Restrictions.or(confirmada, judice));

    //criteria.addOrder(Order.asc("c.nome"));
    return criteria.list();
}

From source file:br.ufc.ivela.commons.dao.GenericDaoImpl.java

License:Open Source License

public List<T> getLastRecords(final String fieldToOrder, final int orderType, final int number) {
    HibernateCallback callback = new HibernateCallback() {

        public Object doInHibernate(Session session) throws HibernateException {

            Criteria criteria = session.createCriteria(clazz);

            if (number != 0) {
                criteria.setMaxResults(number);
            }//from  w w w  .j  av  a2s .co  m

            if (orderType == ORDER_DESC) {
                return criteria.addOrder(Order.desc(fieldToOrder)).list();
            } else if (orderType == ORDER_ASC) {
                return criteria.addOrder(Order.asc(fieldToOrder)).list();
            } else {
                return criteria.list();
            }

        }
    };
    return (List<T>) getHibernateTemplate().execute(callback);
}

From source file:br.ufg.calendario.dao.CalendarioDao.java

@Transactional(readOnly = true)
public List<Calendario> listar(int first, int pageSize, String sortField, String sortOrder,
        Map<String, Object> filters) {
    Session session = sessionFactory.getCurrentSession();
    Criteria criteria = session.createCriteria(Calendario.class);
    criteria.setFirstResult(first);//from w w w .ja v  a2 s. c  o  m
    criteria.setMaxResults(pageSize);
    if ((sortField != null && !sortField.isEmpty()) && (sortOrder != null && !sortOrder.isEmpty())) {
        if (sortOrder.equals("ASCENDING")) {
            criteria.addOrder(Order.asc(sortField));
        }
        if (sortOrder.equals("DESCENDING")) {
            criteria.addOrder(Order.desc(sortField));
        }
    }
    if (filters != null && !filters.isEmpty()) {
        for (Entry<String, Object> filter : filters.entrySet()) {
            criteria.add(Restrictions.eq(filter.getKey(), filter.getValue()));
        }
    }
    return criteria.list();
}

From source file:br.ufg.calendario.dao.EventoDao.java

@Transactional(readOnly = true)
public List<Evento> listar(int first, int pageSize, String sortField, String sortOrder,
        Map<String, Object> filters) {
    Session session = sessionFactory.getCurrentSession();
    Criteria criteria = session.createCriteria(Evento.class);
    criteria.setFirstResult(first);//from  ww w  . j  a  v  a2s  .c om
    criteria.setMaxResults(pageSize);

    if ((sortField != null && !sortField.isEmpty()) && (sortOrder != null && !sortOrder.isEmpty())) {
        if (sortOrder.equals("ASCENDING")) {
            criteria.addOrder(Order.asc(sortField));
        }
        if (sortOrder.equals("DESCENDING")) {
            criteria.addOrder(Order.desc(sortField));
        }
    } else {
        criteria.addOrder(Order.asc("id"));
    }
    if (filters != null && !filters.isEmpty()) {
        for (String key : filters.keySet()) {
            if (key.equals("termo")) {
                List foundList = buscarTermo(session, filters.get("termo").toString());
                if (foundList.size() > 0) {
                    criteria.add(Restrictions.in("id", foundList));
                } else {
                    criteria.add(Restrictions.or(
                            Restrictions.like("assunto", filters.get(key).toString(), MatchMode.ANYWHERE)
                                    .ignoreCase(),
                            Restrictions.like("descricao", filters.get(key).toString(), MatchMode.ANYWHERE)
                                    .ignoreCase()));
                }
            }

            if (key.equals("interessado")) {
                Interessado interessado = (Interessado) filters.get(key);
                System.out.println("interessado: " + interessado.getNome());
                criteria.createCriteria("interessado").add(Restrictions.eq("id", interessado.getId()));
            }

            if (key.equals("regional")) {
                Regional regional = (Regional) filters.get(key);
                System.out.println("regional: " + regional.getNome());
                criteria.createCriteria("regional").add(Restrictions.eq("id", regional.getId()));
            }

            if (key.equals("periodo")) {
                Map periodo = (Map) filters.get(key);
                criteria.add(Restrictions
                        .or(Restrictions.between("inicio", periodo.get("inicio"), periodo.get("termino")))
                        .add(Restrictions.between("termino", periodo.get("inicio"), periodo.get("termino"))));
            }

            if (key.equals("calendario")) {
                criteria.createAlias("calendario", "c");
                criteria.add(Restrictions.eq("c.ano", ((Calendario) filters.get(key)).getAno()));
            }

        }
    }
    if (filters == null || !filters.containsKey("calendario")) {
        criteria.createAlias("calendario", "c");
        criteria.add(Restrictions.eq("c.ativo", true));
    }
    criteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
    List<Evento> resultado = criteria.list();
    for (Evento evt : resultado) {
        Hibernate.initialize(evt.getInteressado());
        Hibernate.initialize(evt.getRegional());
    }
    return resultado;
}

From source file:br.ufg.calendario.dao.InteressadoDao.java

@Transactional(readOnly = true)
public List<Interessado> listar(int first, int pageSize, String sortField, String sortOrder,
        Map<String, Object> filters) {
    Session session = sessionFactory.getCurrentSession();
    Criteria criteria = session.createCriteria(Interessado.class);
    criteria.setFirstResult(first);//from w w w  .ja v  a 2  s  .  co m
    criteria.setMaxResults(pageSize);
    if ((sortField != null && !sortField.isEmpty()) && (sortOrder != null && !sortOrder.isEmpty())) {
        if (sortOrder.equals("ASCENDING")) {
            criteria.addOrder(Order.asc(sortField));
        }
        if (sortOrder.equals("DESCENDING")) {
            criteria.addOrder(Order.desc(sortField));
        }
    }
    if (filters != null && !filters.isEmpty()) {
        for (Entry<String, Object> filter : filters.entrySet()) {
            criteria.add(Restrictions.eq(filter.getKey(), filter.getValue()));
        }
    }
    return criteria.list();
}

From source file:br.ufg.calendario.dao.UsuarioDao.java

@Transactional(readOnly = true)
public List<Usuario> listar(int first, int pageSize, String sortField, String sortOrder,
        Map<String, Object> filters) {
    Session session = sessionFactory.getCurrentSession();
    Criteria criteria = session.createCriteria(Usuario.class);
    criteria.setFirstResult(first);/* w  w  w  .  j  a  v  a2s  .c  o m*/
    criteria.setMaxResults(pageSize);
    if ((sortField != null && !sortField.isEmpty()) && (sortOrder != null && !sortOrder.isEmpty())) {
        if (sortOrder.equals("ASCENDING")) {
            criteria.addOrder(Order.asc(sortField));
        }
        if (sortOrder.equals("DESCENDING")) {
            criteria.addOrder(Order.desc(sortField));
        }
    } else {
        criteria.addOrder(Order.asc("id"));
    }
    if (filters != null && !filters.isEmpty()) {
        for (String key : filters.keySet()) {
            if (key.equals("termo")) {
                criteria.add(Restrictions.or(
                        Restrictions.like("nome", filters.get(key).toString(), MatchMode.ANYWHERE).ignoreCase(),
                        Restrictions.like("login", filters.get(key).toString(), MatchMode.ANYWHERE)
                                .ignoreCase()));
            }

            if (key.equals("perfil")) {
                PerfilEnum p = (PerfilEnum) filters.get(key);
                criteria.add(Restrictions.eq("perfil", p));
            }

        }
    }
    criteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
    List<Usuario> resultado = criteria.list();
    for (Usuario u : resultado) {
        Hibernate.initialize(u.getPerfil());
    }
    return resultado;
}

From source file:ca.myewb.controllers.common.EventList.java

License:Open Source License

private void addPagination(int startPage, int eventsPerPage, Criteria criteria) {
    if (eventsPerPage > 0) {
        criteria.setMaxResults(eventsPerPage);
    }/*  ww w  .j a va  2s . c o m*/

    if (startPage > 0) {
        criteria.setFirstResult(startPage);
    }
}

From source file:ca.myewb.controllers.common.Member.java

License:Open Source License

private void searchMode(Context ctx) throws Exception, RedirectionException {
    MemberSearchForm searchForm = null;//from ww w.  j  a va2 s .co  m
    List result = null;

    if (currentUser.isAdmin()) {
        result = hibernateSession.createQuery("FROM GroupChapterModel where visible=true").list();
    }

    // run search, store results in temp list
    if (requestParams.get("Advanced") != null) {
        searchForm = new MemberSearchForm(getInterpageVar("membersearchtarget") + "/search", requestParams,
                true, result);
        ctx.put("advanced", new Boolean(true));
    } else {
        searchForm = new MemberSearchForm(getInterpageVar("membersearchtarget") + "/search", requestParams,
                false, result);
    }

    Message m = searchForm.validate();

    if (m != null) // validation failed, redirect to self, next time we'll be entering the next block
    {
        // Display error and prompt user to fix
        throw getValidationException(searchForm, m, (String) getInterpageVar("membersearchtarget"));
    }

    //form validation succeeded!
    String first = searchForm.getParameter("Firstname");
    String last = searchForm.getParameter("Lastname");
    String email = searchForm.getParameter("Email");
    String city = searchForm.getParameter("City", false);
    String province = searchForm.getParameter("Province", false);
    String lang = searchForm.getParameter("Language", false);
    String gender = searchForm.getParameter("Gender", false);
    String birth = searchForm.getParameter("Birth", false);
    String student = searchForm.getParameter("Student", false);
    String username = searchForm.getParameter("Username", false);

    Criteria crit = hibernateSession.createCriteria(UserModel.class);

    if ((username != null) && !username.equals("")) {
        crit.add(Restrictions.like("username", "%" + username.trim() + "%"));
    }

    if ((first != null) && !first.equals("")) {
        crit.add(Restrictions.like("firstname", "%" + first.trim() + "%"));
    }

    if ((last != null) && !last.equals("")) {
        crit.add(Restrictions.like("lastname", "%" + last.trim() + "%"));
    }

    if ((email != null) && !email.equals("")) {
        List ids = HibernateUtil.currentSession()
                .createSQLQuery("SELECT userid FROM useremails e WHERE e.email LIKE '%" + email.trim() + "%'")
                .list();
        if (!ids.isEmpty()) {
            crit.add(Restrictions.in("id", ids));
        } else {
            crit.add(Restrictions.eq("email", "###invalidemail###")); //so that no results are given
        }
    }

    if ((city != null) && !city.equals("")) {
        crit.add(Restrictions.like("address", "%\n%" + city.trim() + "%\n%"));
    }

    if ((province != null) && !province.equals("")) {
        crit.add(Restrictions.like("address", "%\n%" + province.trim() + "%\n%"));
    }

    if ((lang != null) && !lang.equals("")) {
        crit.add(Restrictions.eq("language", lang.trim()));
    }

    if ((gender != null) && !gender.equals("")) {
        crit.add(Restrictions.eq("gender", gender.trim()));
    }

    if ((birth != null) && !birth.equals("")) {
        crit.add(Restrictions.eq("birth", new Integer(birth)));
    }

    if ((student != null) && !student.equals("")) {
        crit.add(Restrictions.eq("student", new Boolean(student)));
    }

    // Get "my" own lead groups, since I can only
    // see people in groups I lead
    crit.createAlias("roles", "r");
    crit.add(Restrictions.isNull("r.end"));

    if (!currentUser.isAdmin()) {
        crit.add(Restrictions.in("r.group", currentUser.getGroups('l')));
    } else {
        GroupChapterModel chapter = null;

        if (searchForm.getParameter("Chapter", false) != null) {
            if (!searchForm.getParameter("Chapter", false).equals("")) {
                chapter = (GroupChapterModel) hibernateSession.get(GroupChapterModel.class,
                        new Integer(searchForm.getParameter("Chapter", false)));
            }
        }

        if (chapter != null) {
            crit.add(Restrictions.eq("r.group", chapter));
            crit.add(Restrictions.eq("r.level", new Character('m')));
        }

        //don't filter out deleted users!
    }

    crit.add(Restrictions.ne("id", new Integer(1)));

    crit.addOrder(Order.asc("lastname"));
    crit.addOrder(Order.asc("firstname"));
    crit.setProjection(Projections.groupProperty("id"));
    crit.setMaxResults(101);

    List uniqueResultsList = crit.list();
    Vector<UserModel> uniqueResults = new Vector<UserModel>();

    if (uniqueResultsList.size() < 101) {
        Iterator iter = uniqueResultsList.iterator();

        while (iter.hasNext()) {
            Integer i = (Integer) iter.next();

            // This try/catch block is a workaround to the deleted-admin-causes-cgilib-blowup bug
            try {
                uniqueResults.add((UserModel) hibernateSession.get(UserModel.class, i));
            } catch (Exception e) {
                log.warn("Unable to add user to usersearch: id " + i.toString());
            }
        }
    } else {
        ctx.put("tooMany", "yes");
    }

    setInterpageVar("membersearchtempresults", uniqueResultsList);
    ctx.put("tempresults", uniqueResults); //NOT the ids, but the users
    ctx.put("searchmode", "yes");
    if (searchForm == null) {
        log.info("search form was null!");
        throw new RedirectionException(getInterpageVar("membersearchtarget") + "/new");
    }

    ctx.put("form", searchForm);
    ctx.put("target", getInterpageVar("membersearchtarget"));
}

From source file:ca.myewb.controllers.common.PostList.java

License:Open Source License

private void addPagination(int start, int limit, Criteria criteria) {
    if (limit > 0) {
        criteria.setMaxResults(limit);
    }//from w w w.  j  a va  2 s. co  m

    if (start > 0) {
        criteria.setFirstResult(start);
    }
}

From source file:ca.myewb.controllers.common.WhiteboardList.java

License:Open Source License

private void addPagination(int startPage, int whiteboardsPerPage, Criteria criteria) {
    if (whiteboardsPerPage > 0) {
        criteria.setMaxResults(whiteboardsPerPage);
    }//w  w w  .  j a v a 2s .c  o  m

    if (startPage > 0) {
        criteria.setFirstResult(startPage);
    }
}