Example usage for org.hibernate Criteria addOrder

List of usage examples for org.hibernate Criteria addOrder

Introduction

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

Prototype

public Criteria addOrder(Order order);

Source Link

Document

Add an Order ordering to the result set.

Usage

From source file:br.ufg.reqweb.dao.RequerimentoDao.java

@Transactional(readOnly = true)
public List<Requerimento> find(String sortField, String sortOrder, Map<String, Object> filters) {
    if (filters == null) {
        filters = new HashMap();
    }//from   w ww. j av  a2s  . com
    try {
        Criteria criteria = this.sessionFactory.getCurrentSession().createCriteria(Requerimento.class);
        for (String field : filters.keySet()) {
            /**
             * login eq / tipoRequerimento eq / termo like / dataCriacao
             * between
             */
            if (field.equals("login")) {
                criteria.createAlias("discente", "d");
                criteria.add(Restrictions.and(Restrictions.eq("d.login", filters.get(field))));
            }
            if (field.equals("turmas")) {
                criteria.createAlias("itemRequerimentoList", "i");
                List<Turma> turmas = (List<Turma>) filters.get(field);
                criteria.add(Restrictions.and(Restrictions.in("i.turma", turmas)));
            }
            if (field.equals("tipoRequerimento")) {
                criteria.add(Restrictions.and(Restrictions.eq(field, filters.get(field))));
            }
            if (field.equals("termo")) {
                criteria.createAlias("discente", "d");
                criteria.add(Restrictions.or(Restrictions.eq("d.matricula", filters.get("termo")), Restrictions
                        .like("d.nome", filters.get("termo").toString(), MatchMode.ANYWHERE).ignoreCase()));
            }
            if (field.equals("curso")) {
                criteria.createAlias("discente.perfilList", "p");
                criteria.add(Restrictions.and(Restrictions.eq("p.curso", filters.get(field))));
            }
            if (field.equals("dataCriacao")) {
                Date[] arrayDate = (Date[]) filters.get("dataCriacao");
                criteria.add(Restrictions.and(Restrictions.between("dataCriacao", arrayDate[0], arrayDate[1])));
            }
        }
        if ((sortField != null && !sortField.isEmpty()) && (sortOrder != null && !sortOrder.isEmpty())) {
            if (sortOrder.toLowerCase().equals("asc")) {
                criteria.addOrder(Property.forName(sortField).asc());
            }
            if (sortOrder.toLowerCase().equals("desc")) {
                criteria.addOrder(Property.forName(sortField).desc());
            }
        }
        criteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
        return criteria.list();
    } catch (HibernateException e) {
        System.out.println("query error: " + e.getMessage());
        return new ArrayList<>();
    }
}

From source file:br.ufg.reqweb.dao.TurmaDao.java

@Transactional(readOnly = true)
public List<Turma> find(int firstResult, int maxResult, String sortField, String sortOrder,
        Map<String, Object> filters) {
    if (filters == null) {
        filters = new HashMap();
    }//from   w  w w. j  a  v  a2s.  co  m
    try {
        Criteria criteria = this.sessionFactory.getCurrentSession().createCriteria(Turma.class);
        criteria.createAlias("disciplina", "d");
        for (String field : filters.keySet()) {
            if (field.equals("termo")) {
                criteria.add(Restrictions.and(Restrictions
                        .like("d.nome", filters.get(field).toString(), MatchMode.ANYWHERE).ignoreCase()));
            }
            if (field.equals("periodo")) {
                criteria.add(Restrictions.and(Restrictions.eq("periodo", filters.get(field))));
            }
            if (field.equals("curso")) {
                criteria.add(Restrictions.and(Restrictions.eq("d.curso", filters.get(field))));
            }
        }
        if ((sortField != null && !sortField.isEmpty()) && (sortOrder != null && !sortOrder.isEmpty())) {
            System.out.format("sorted by: %s, ordering %s\n", sortField, sortOrder);
            if (sortOrder.toLowerCase().equals("asc")) {
                criteria.addOrder(Property.forName(sortField).asc());
            }
            if (sortOrder.toLowerCase().equals("desc")) {
                criteria.addOrder(Property.forName(sortField).desc());
            }
        }
        criteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
        return criteria.list();
    } catch (HibernateException e) {
        System.out.println("query error: " + e.getMessage());
        return new ArrayList<>();
    }
}

From source file:br.ufmg.hc.telessaude.diagnostico.dominio.dao.ExameDAOLocal.java

public List<Exame> consultar(Integer id, String nomePaciente, Date inicio, Date fim) throws DAOException {
    ArrayList<Criterion> restrict = new ArrayList();
    if (id != null) {
        restrict.add(Restrictions.eq("id", id));
    } else {//  ww  w . j  av a2  s  . co m
        if (nomePaciente != null && !nomePaciente.isEmpty()) {
            restrict.add(Restrictions.ilike("pc.nome", nomePaciente, MatchMode.ANYWHERE));
        }
        if (inicio != null) {
            restrict.add(Restrictions.ge("datainclusao", inicio));
        }
        if (fim != null) {
            restrict.add(Restrictions.le("datainclusao", fim));
        }
    }
    try {
        final DetachedCriteria crit = DetachedCriteria.forClass(c);
        final Criteria criteria = crit.getExecutableCriteria(HibernateUtil.currentSession());

        crit.createAlias("paciente", "pc");
        crit.createAlias("status", "st");

        criteria.setProjection(Projections.projectionList().add(Projections.property("id"))
                .add(Projections.property("pc.nome")).add(Projections.property("pc.datanascimento"))
                .add(Projections.property("datainclusao")).add(Projections.property("st.nome")));

        criteria.addOrder(Order.desc("datainclusao"));

        for (final Criterion cri : restrict) {
            criteria.add(cri);
        }

        final List<Object[]> arrays = criteria.list();
        final List<Exame> exames = new ArrayList<>();

        for (Object[] array : arrays) {
            final Exame exame = new Exame(Integer.parseInt(String.valueOf(array[0])));
            exame.setPaciente(new Paciente());
            exame.getPaciente().setNome(String.valueOf(array[1]));
            exame.getPaciente().setDatanascimento((Date) array[2]);
            exame.setDatainclusao((Date) array[3]);
            exame.setStatus(new Status());
            exame.getStatus().setNome(String.valueOf(array[4]));

            exames.add(exame);
        }

        return exames;

    } catch (HibernateException ex) {
        throw new DAOException(ex.getMessage());
    }

}

From source file:by.telecom.subscriberapp.DAO.LogDaoImpl.java

@Override
public List<Log> getByParameter(String name, Date dateStart, Date dateEnd, String type, String comment,
        String sort, String orderType) {
    Session session = null;//from   w w  w.j  a v  a  2  s  .c  om
    List<Log> logs = new ArrayList<Log>();
    try {
        session = HibernateUtil.getSessionFactory().openSession();
        session.beginTransaction();
        Criteria criteria = session.createCriteria(Log.class).add(Restrictions.ge("date", dateStart))
                .add(Restrictions.le("date", dateEnd)).add(Restrictions.like("type", "%" + type + "%"))
                .add(Restrictions.like("comment", "%" + comment + "%"));
        Order order = Order.asc(sort);
        if (orderType.equals("desc"))
            order = Order.desc(sort);
        if (sort.equals("name"))
            criteria = criteria.createCriteria("user").add(Restrictions.like("name", "%" + name + "%"))
                    .addOrder(order);
        else
            criteria = criteria.addOrder(order).createCriteria("user")
                    .add(Restrictions.like("name", "%" + name + "%"));

        logs = criteria.list();
        session.getTransaction().commit();
    } catch (Exception e) {
        e.printStackTrace(System.out);
    } finally {
        if (session != null && session.isOpen()) {
            session.close();
        }
    }
    return logs;
}

From source file:by.telecom.subscriberapp.DAO.PhoneDaoImpl.java

@Override
public List<Phone> getAll(String sort, String orderType) {
    Session session = null;/*from  www  . j  ava  2  s  .co m*/
    List<Phone> all = new ArrayList<Phone>();
    try {
        session = HibernateUtil.getSessionFactory().openSession();
        session.beginTransaction();
        Criteria criteria = session.createCriteria(Phone.class);
        Order order = Order.asc(sort);
        if (sort.equals("name"))
            criteria = criteria.createCriteria("subscriber");
        if (orderType.equals("desc"))
            order = Order.desc(sort);
        all = criteria.addOrder(order).list();
    } catch (Exception e) {
        e.printStackTrace(System.out);
    } finally {
        if (session != null && session.isOpen()) {
            session.close();
        }
    }
    return all;
}

From source file:by.telecom.subscriberapp.DAO.PhoneDaoImpl.java

@Override
public List<Phone> getByParameter(String number, String band, String security, String scv, String adsl,
        String name, String sort, String orderType) {
    Session session = null;//from   w  w w  . j a v a2 s . co  m
    List<Phone> phones = new ArrayList<Phone>();
    try {
        session = HibernateUtil.getSessionFactory().openSession();
        session.beginTransaction();
        Criteria criteria = session.createCriteria(Phone.class).add(Restrictions.like("number", number + "%"))
                .add(Restrictions.like("band", band + "%")).add(Restrictions.like("security", security + "%"))
                .add(Restrictions.like("scv", scv + "%")).add(Restrictions.like("adsl", adsl + "%"));
        Order order = Order.asc(sort);
        if (orderType.equals("desc"))
            order = Order.desc(sort);
        if (sort.equals("name"))
            criteria = criteria.createCriteria("subscriber").add(Restrictions.like("name", "%" + name + "%"))
                    .addOrder(order);
        else
            criteria = criteria.addOrder(order).createCriteria("subscriber")
                    .add(Restrictions.like("name", "%" + name + "%"));

        phones = criteria.list();
        session.getTransaction().commit();
    } catch (Exception e) {
        e.printStackTrace(System.out);
    } finally {
        if (session != null && session.isOpen()) {
            session.close();
        }
    }
    return phones;
}

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

License:Open Source License

public Collection<EventModel> listVisibleEventsBetweenDates(Date start, Date end, GroupChapterModel chapter)
        throws HibernateException {
    Criteria criteria = hibernateSession.createCriteria(EventModel.class);

    LogicalExpression singleDayEvents = Restrictions.and(Restrictions.ge("startDate", start),
            Restrictions.le("endDate", end));
    LogicalExpression endsToday = Restrictions.and(Restrictions.lt("startDate", start),
            Restrictions.and(Restrictions.ge("endDate", start), Restrictions.le("endDate", end)));
    LogicalExpression startsToday = Restrictions.and(
            Restrictions.and(Restrictions.ge("startDate", start), Restrictions.le("startDate", end)),
            Restrictions.gt("endDate", end));
    LogicalExpression ongoing = Restrictions.and(Restrictions.lt("startDate", start),
            Restrictions.gt("endDate", end));

    criteria.add(Restrictions.or(singleDayEvents,
            Restrictions.or(endsToday, Restrictions.or(startsToday, ongoing))));

    if (chapter == null) {
        if (!currentUser.isAdmin()) {
            criteria.add(Restrictions.in("group", Permissions.visibleGroups(currentUser, true)));
        } else {//from   w  ww  . j  av a  2s.c om
            List<GroupModel> adminGroups = Helpers.getNationalRepLists(true, true);
            adminGroups.add(Helpers.getGroup("Exec"));
            adminGroups.add(Helpers.getGroup("ProChaptersExec"));

            criteria.add(Restrictions.in("group", adminGroups));
        }
    } else {
        criteria.add(Restrictions.in("group", Permissions.visibleGroupsInChapter(currentUser, chapter)));
    }

    criteria.addOrder(Order.asc("startDate"));
    criteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);

    return new SafeHibList<EventModel>(criteria).list();
}

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

License:Open Source License

public List<EventModel> listPaginatedVisibleEvents(String filter, int startPage, int eventsPerPage,
        Date endAfter) throws HibernateException {
    Criteria criteria = hibernateSession.createCriteria(EventModel.class);

    if (!currentUser.isAdmin()) {
        log.info("EventList visible groups added to criteria");
        criteria.add(Restrictions.in("group", Permissions.visibleGroups(currentUser, true)));
    }//from   w w  w .  ja v  a2 s.  co  m

    criteria.addOrder(Order.asc("startDate"));
    criteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);

    addBooleanFilters(endAfter, criteria);
    addFilter(filter, criteria);
    addPagination(startPage, eventsPerPage, criteria);

    return getUniqueEventList(criteria);
}

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

License:Open Source License

public int visibleEventCount(String filter, Date endAfter) throws HibernateException {
    Criteria criteria = hibernateSession.createCriteria(EventModel.class);

    if (!currentUser.isAdmin()) {
        criteria.add(Restrictions.in("group", Permissions.visibleGroups(currentUser, true)));
    }/*from   ww w. j  ava 2s.  co m*/

    addBooleanFilters(endAfter, criteria);
    addFilter(filter, criteria);

    criteria.addOrder(Order.asc("startDate"));
    criteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);

    return getUniqueEventCount(criteria);
}

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 w  ww .  java  2  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"));
}