Example usage for org.hibernate Criteria setProjection

List of usage examples for org.hibernate Criteria setProjection

Introduction

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

Prototype

public Criteria setProjection(Projection projection);

Source Link

Document

Used to specify that the query results will be a projection (scalar in nature).

Usage

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

@Transactional(readOnly = true)
public int rowCount(String termo) {
    Session session = sessionFactory.getCurrentSession();
    Criteria criteria = session.createCriteria(Interessado.class);
    if (termo != null && !termo.isEmpty()) {
        criteria.add(Restrictions.or(Restrictions.like("sigla", termo.trim(), MatchMode.ANYWHERE).ignoreCase(),
                Restrictions.like("nome", termo.trim(), MatchMode.ANYWHERE).ignoreCase()));
    }//from  www .java2 s.  c o  m
    return ((Long) criteria.setProjection(Projections.rowCount()).uniqueResult()).intValue();
}

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

@Transactional(readOnly = true)
public int rowCount() {
    Session session = sessionFactory.getCurrentSession();
    Criteria criteria = session.createCriteria(Regional.class);
    return ((Long) criteria.setProjection(Projections.rowCount()).uniqueResult()).intValue();
}

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

@Transactional(readOnly = true)
public int rowCount(String termo) {
    Session session = sessionFactory.getCurrentSession();
    Criteria criteria = session.createCriteria(Regional.class);
    if (termo != null && !termo.isEmpty()) {
        criteria.add(Restrictions.like("nome", termo.trim(), MatchMode.ANYWHERE).ignoreCase());
    }/*from   w  ww  .j av  a 2s .c  om*/
    return ((Long) criteria.setProjection(Projections.rowCount()).uniqueResult()).intValue();
}

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

@Transactional(readOnly = true)
public int rowCount() {
    Session session = sessionFactory.getCurrentSession();
    Criteria criteria = session.createCriteria(Usuario.class);
    return ((Long) criteria.setProjection(Projections.rowCount()).uniqueResult()).intValue();
}

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

@Transactional(readOnly = true)
public int rowCount(Map<String, Object> filters) {
    Session session = sessionFactory.getCurrentSession();
    Criteria criteria = session.createCriteria(Usuario.class);
    for (String key : filters.keySet()) {
        if (key.equals("nome")) {
            criteria.add(//from w  w w  .  ja  v  a2 s . c om
                    Restrictions.like("nome", filters.get(key).toString(), MatchMode.ANYWHERE).ignoreCase());
        }

        if (key.equals("login")) {
            criteria.add(
                    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));
        }
    }
    return ((Long) criteria.setProjection(Projections.rowCount()).uniqueResult()).intValue();
}

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

@Transactional(readOnly = true)
public int count(Map<String, Object> filters) {
    if (filters == null) {
        filters = new HashMap();
    }//from  www .  java2 s.c o 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))));
            }
        }
        criteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
        return ((Long) criteria.setProjection(Projections.rowCount()).uniqueResult()).intValue();
    } catch (HibernateException e) {
        System.out.println("query error: " + e.getMessage());
        return 0;
    }

}

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 {/*  w w w  .  j a v a2 s.c o 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:br.ufmg.hc.telessaude.diagnostico.dominio.dao.LaudoDAOLocal.java

@Override
public List<Laudo> consultarPorIdExame(Integer id) throws DAOException {
    try {//from  w ww. ja  v  a2  s .  c om
        final DetachedCriteria crit = DetachedCriteria.forClass(c);
        final Criteria criteria = crit.getExecutableCriteria(HibernateUtil.currentSession());

        criteria.setProjection(Projections.projectionList().add(Projections.property("id"))
                .add(Projections.property("datainicio")).add(Projections.property("conteudo")));

        criteria.add(Restrictions.eq("exame.id", id));

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

        for (Object[] array : arrays) {
            final Laudo laudo = new Laudo(Integer.parseInt(String.valueOf(array[0])));
            laudo.setDatainicio((Date) array[1]);
            laudo.setConteudo(array[2].toString());
            laudos.add(laudo);
        }

        return laudos;

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

}

From source file:by.andrew.pakhomov.testtask.web.controller.SpentTimeRecordController.java

@RequestMapping("/bydevelopers")
public String getSpentTimeBetweenDatesSumByDevelopers(
        @RequestParam(name = "startDate", required = false) String startDate,
        @RequestParam(name = "finishDate", required = false) String finishDate, Model model) {
    model.addAttribute("records", Collections.emptyMap());
    if (startDate == null && finishDate == null) {
        return "report-spent-time-by-developers";
    } else {//from ww w  . j  a v a 2 s . c o m
        model.addAttribute("startDate", startDate);
        model.addAttribute("finishDate", finishDate);
    }

    List<String> errors = new ArrayList<>(2);

    Date startDateTime = null;
    Date finishDateTime = null;
    try {
        startDateTime = DATE_FORMAT.parse(startDate);
    } catch (ParseException ex) {
        errors.add(
                "       --");
    }
    try {
        finishDateTime = DATE_FORMAT.parse(finishDate);
    } catch (ParseException ex) {
        errors.add(
                "       --");
    }

    if (!errors.isEmpty()) {
        this.addFormErrors(model, errors.toArray(new String[errors.size()]));
        return "report-spent-time-by-developers";
    }

    final Date finalStartDate = startDateTime;
    final Date finalFinishDate = finishDateTime;

    this.executeSafely(model, (Session session) -> {
        Criteria cr = session.createCriteria(SpentTimeRecord.class);
        //            cr.add(Restrictions.between("registrationDate", finalStartDate, finalFinishDate));

        cr.setProjection(Projections.projectionList().add(Projections.sum("spentTimeInSeconds"))
                .add(Projections.groupProperty("employee")));

        List<Object[]> records = cr.list();
        Map<String, Long> report = new HashMap<>();
        for (Object[] current : records) {
            report.put((String) current[1], (long) current[0]);
        }

        model.addAttribute("records", report);
        return true;
    });

    return "report-spent-time-by-developers";
}

From source file:c14_hibernate.ManageEmployee.java

public void totalSalary() {
    Session session = factory.openSession();
    Transaction tx = null;/*  ww w  .  j  a  v  a2  s.com*/
    try {
        tx = session.beginTransaction();
        Criteria cr = session.createCriteria(Employee.class);
        // To get total salary.
        cr.setProjection(Projections.sum("salary"));
        List totalSalary = cr.list();
        System.out.println("Total Salary: " + totalSalary.get(0));
        tx.commit();
    } catch (HibernateException e) {
        if (tx != null)
            tx.rollback();
        e.printStackTrace();
    } finally {
        session.close();
    }
}