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.com.webbudget.domain.model.repository.tools.MessageRepository.java

License:Open Source License

/**
 * /*from   ww w.  j  a  v a  2s  .  c om*/
 * @param sender
 * @param filter
 * @param pageRequest
 * @return 
 */
@Override
public Page<Message> listSent(User sender, String filter, PageRequest pageRequest) {

    final Criteria criteria = this.createCriteria();

    if (filter != null) {
        criteria.add(Restrictions.or(Restrictions.ilike("title", "%" + filter + "%"),
                Restrictions.ilike("content", "%" + filter + "%")));
    }

    criteria.add(Restrictions.eq("deleted", false));
    criteria.add(Restrictions.eq("sender", sender));

    // projetamos para pegar o total de paginas possiveis
    criteria.setProjection(Projections.count("id"));

    final Long totalRows = (Long) criteria.uniqueResult();

    // limpamos a projection para que a criteria seja reusada
    criteria.setProjection(null);
    criteria.setResultTransformer(Criteria.ROOT_ENTITY);

    // paginamos
    criteria.setFirstResult(pageRequest.getFirstResult());
    criteria.setMaxResults(pageRequest.getPageSize());

    if (pageRequest.getSortDirection() == PageRequest.SortDirection.ASC) {
        criteria.addOrder(Order.asc(pageRequest.getSortField()));
    } else if (pageRequest.getSortDirection() == PageRequest.SortDirection.DESC) {
        criteria.addOrder(Order.desc(pageRequest.getSortField()));
    }

    // montamos o resultado paginado
    return new Page<>(criteria.list(), totalRows);
}

From source file:br.com.webbudget.domain.model.repository.tools.UserMessageRepository.java

License:Open Source License

/**
 * /* w w  w  .j a v a2s.c  o m*/
 * @param recipient
 * @return 
 */
@Override
public long countUnread(User recipient) {

    final Criteria criteria = this.createCriteria();

    criteria.add(Restrictions.eq("read", false));
    criteria.add(Restrictions.eq("recipient", recipient));

    // projetamos para pegar o total de paginas possiveis
    criteria.setProjection(Projections.count("id"));

    return (Long) criteria.uniqueResult();
}

From source file:br.com.webbudget.domain.model.repository.tools.UserMessageRepository.java

License:Open Source License

/**
 * /*from   ww  w.  ja va  2s  .  c o m*/
 * @param recipient
 * @param filter
 * @param pageRequest
 * @return 
 */
@Override
public Page<UserMessage> listReceived(User recipient, String filter, PageRequest pageRequest) {

    final Criteria criteria = this.createCriteria();

    if (filter != null) {
        criteria.createAlias("message", "ms");
        criteria.add(Restrictions.or(Restrictions.ilike("ms.title", "%" + filter + "%"),
                Restrictions.ilike("ms.content", "%" + filter + "%")));
    }

    criteria.add(Restrictions.eq("deleted", false));
    criteria.add(Restrictions.eq("recipient", recipient));

    // projetamos para pegar o total de paginas possiveis
    criteria.setProjection(Projections.count("id"));

    final Long totalRows = (Long) criteria.uniqueResult();

    // limpamos a projection para que a criteria seja reusada
    criteria.setProjection(null);
    criteria.setResultTransformer(Criteria.ROOT_ENTITY);

    // paginamos
    criteria.setFirstResult(pageRequest.getFirstResult());
    criteria.setMaxResults(pageRequest.getPageSize());

    if (pageRequest.getSortDirection() == PageRequest.SortDirection.ASC) {
        criteria.addOrder(Order.asc(pageRequest.getSortField()));
    } else if (pageRequest.getSortDirection() == PageRequest.SortDirection.DESC) {
        criteria.addOrder(Order.desc(pageRequest.getSortField()));
    }

    // montamos o resultado paginado
    return new Page<>(criteria.list(), totalRows);
}

From source file:br.gov.jfrj.siga.ex.bl.ExBL.java

License:Open Source License

public void numerarTudo(int aPartirDe) {
    List<ExDocumento> list = new ArrayList<ExDocumento>();

    final Criteria countCrit = dao().getSessao().createCriteria(ExDocumento.class)
            .add(Restrictions.gt("idDoc", new Long(aPartirDe)));
    countCrit.setProjection(Projections.rowCount());
    Integer totalDocs = ((Long) countCrit.uniqueResult()).intValue();

    final Criteria crit = dao().getSessao().createCriteria(ExDocumento.class)
            .add(Restrictions.gt("idDoc", new Long(aPartirDe)));
    crit.setMaxResults(60);//from  w  w w  .java  2s .  c o  m
    crit.addOrder(Order.asc("idDoc"));

    int index = 0;

    do {
        long inicio = System.currentTimeMillis();
        //System.gc();
        iniciarAlteracao();
        crit.setFirstResult(index);
        list = crit.list();
        for (ExDocumento doc : list) {
            index++;
            try {
                for (ExMovimentacao m : doc.getExMovimentacaoSet()) {
                    m.setNumPaginas(m.getContarNumeroDePaginas());
                    dao().gravar(m);
                }
            } catch (Throwable e) {
                System.out.println("Erro ao marcar o doc " + doc);
                e.printStackTrace();
            }
            if (index % 50 == 0) {
                //               System.gc();
            }
            System.out.print(doc.getIdDoc() + " ok - ");
        }
        ExDao.commitTransacao();
        dao().getSessao().clear();
        long duracao = System.currentTimeMillis() - inicio;
        System.out.println();
        System.out.println(new SimpleDateFormat("HH:mm:ss").format(new Date()) + " " + String.valueOf(index)
                + " numerados de " + totalDocs);
    } while (list.size() > 0);

    //System.gc();
}

From source file:br.gov.jfrj.siga.ex.bl.ExBL.java

License:Open Source License

public void marcarTudo(int primeiro, int ultimo, boolean efetivar, boolean apenasTemporalidade,
        PrintWriter out) {/*from  w ww . j  a  va 2 s .  com*/

    List<ExDocumento> list = new ArrayList<ExDocumento>();

    final Criteria countCrit = dao().getSessao().createCriteria(ExDocumento.class)
            .add(Restrictions.ge("idDoc", new Long(primeiro)));
    if (ultimo != 0)
        countCrit.add(Restrictions.le("idDoc", new Long(ultimo)));
    countCrit.setProjection(Projections.rowCount());

    final Criteria crit = dao().getSessao().createCriteria(ExDocumento.class)
            .add(Restrictions.ge("idDoc", new Long(primeiro)));
    if (ultimo != 0)
        crit.add(Restrictions.le("idDoc", new Long(ultimo)));
    crit.setMaxResults(5);
    crit.addOrder(Order.asc("idDoc"));

    out.println("-----------------------------------------------");
    out.print(new SimpleDateFormat("HH:mm:ss").format(new Date()));
    out.print(" - Remarcando documentos.");
    out.print(" Primeiro: ");
    out.println(primeiro);
    if (ultimo != 0) {
        out.print(" Ultimo: ");
        out.println(ultimo);
    }
    if (efetivar)
        out.println("***EFETIVAR!!***");
    out.println("-----------------------------------------------");

    int index = 0;

    do {
        long inicio = System.currentTimeMillis();
        if (efetivar)
            iniciarAlteracao();
        crit.setFirstResult(index);
        list = crit.list();
        for (ExDocumento doc : list) {
            index++;
            StringBuilder msg = new StringBuilder();
            try {

                StringBuilder marcasAnteriores = new StringBuilder();
                for (ExMobil mob : doc.getExMobilSet()) {
                    marcasAnteriores.append(mob.isGeral() ? "0" : mob.getNumSequencia());
                    marcasAnteriores.append(" - ");
                    marcasAnteriores.append(mob.getMarcadoresDescrCompleta(apenasTemporalidade));
                }
                atualizarMarcasTemporalidade(doc);
                StringBuilder marcasPosteriores = new StringBuilder();
                for (ExMobil mob : doc.getExMobilSet()) {
                    marcasPosteriores.append(mob.isGeral() ? "0" : mob.getNumSequencia());
                    marcasPosteriores.append(" - ");
                    marcasPosteriores.append(mob.getMarcadoresDescrCompleta(apenasTemporalidade));
                }

                if (!marcasAnteriores.toString().equals(marcasPosteriores.toString())) {
                    msg.append("Marcas:");
                    msg.append("\n\tAntes: ");
                    msg.append(marcasAnteriores);
                    msg.append("\n\tDepois: ");
                    msg.append(marcasPosteriores);
                }

            } catch (Throwable e) {
                msg.append("ERRO: ");
                msg.append(e.getMessage());
                e.printStackTrace(out);
            }

            if (msg.length() > 0) {
                msg.insert(0, "\n");
                msg.insert(0, doc.getCodigo());
                msg.insert(0, " - ");
                msg.insert(0, new SimpleDateFormat("HH:mm:ss").format(new Date()));
                msg.insert(0, "\n");
                out.println(msg);
            }

        }
        if (efetivar) {
            ExDao.commitTransacao();
            //System.gc();
        }
        dao().getSessao().clear();
    } while (list.size() > 0);

    out.println("\n-----------------------------------------------");
    out.print(new SimpleDateFormat("HH:mm:ss").format(new Date()));
    out.println(" - Fim");
    out.println("-----------------------------------------------");

    //System.gc();
}

From source file:br.gov.mdarte.controleacesso.cd.PerfilDAOImpl.java

@Override
protected Object handleRecuperarSuperPerfil(Session session, String sistema, Integer paginacao, Integer linhas,
        Integer paginas) throws DAOException {
    ProjectionList projectionList = Projections.projectionList();

    projectionList.add(Projections.property("id"));

    Criteria criterios = session.createCriteria(PerfilImpl.class);
    criterios.createAlias("sistema", "sistema");

    criterios.add(Restrictions.eq("superUsuario", Boolean.TRUE));

    criterios.setProjection(projectionList);

    if (sistema != null)
        criterios.add(Restrictions.eq("sistema.nome", sistema));

    ResultTransformer resultTransformer = new ResultTransformer() {

        public Object transformTuple(Object[] result, String[] arg1) {
            return result;
        }//  w ww.jav a 2  s .c o m

        public List transformList(List resultado) {
            List idPerfis = new ArrayList<Long>();

            for (Object[] result : (List<Object[]>) resultado) {
                Collection rows = Arrays.asList(result);
                Iterator iteratorRow = rows.iterator();

                idPerfis.add((Long) iteratorRow.next());
            }

            return idPerfis;
        }
    };

    criterios.setResultTransformer(resultTransformer);

    return criterios;
}

From source file:br.luck.contar.LotofacilContar.java

@Override
protected int obterQuantidade(String bola, long concursoinicio, long concursoFim, int colunaInicio,
        int colunaFim) throws Exception {

    List<Long> lista = new ArrayList<Long>();
    long quantidade = 0;

    for (int coluna = colunaInicio; coluna <= colunaFim; coluna++) {
        Criteria criteria = getSession().createCriteria(LotofacilModel.class);
        String col = String.valueOf((coluna < 10) ? "0" + coluna : coluna);

        criteria.setProjection(Projections.count("bola" + col));
        criteria.add(Restrictions.eq("bola" + col, bola));
        criteria.add(Restrictions.between("concurso", concursoinicio, concursoFim));

        try {/*from  w  w w . j a v a2 s  . c o m*/
            lista.add((Long) criteria.uniqueResult());
        } catch (Exception e) {
            throw new Exception(e.getMessage());
        }
    }
    // Percorre a lista somando os resultados
    for (Long soma : lista) {
        quantidade = quantidade + soma;
    }
    return Integer.parseInt(String.valueOf(quantidade));
}

From source file:br.luck.contar.LotomaniaContar.java

@Override
protected int obterQuantidade(String bola, long concursoinicio, long concursoFim, int colunaInicio,
        int colunaFim) throws Exception {

    List<Long> lista = new ArrayList<Long>();
    long quantidade = 0;

    for (int coluna = colunaInicio; coluna <= colunaFim; coluna++) {
        Criteria criteria = getSession().createCriteria(LotomaniaModel.class);
        String col = String.valueOf((coluna < 10) ? "0" + coluna : coluna);

        criteria.setProjection(Projections.count("bola" + col));
        criteria.add(Restrictions.eq("bola" + col, bola));
        criteria.add(Restrictions.between("concurso", concursoinicio, concursoFim));

        try {/* w  w  w  .ja v  a2 s . c  om*/
            lista.add((Long) criteria.uniqueResult());
        } catch (Exception e) {
            throw new Exception(e.getMessage());
        }
    }
    // Percorre a lista somando os resultados
    for (Long soma : lista) {
        quantidade = quantidade + soma;
    }
    return Integer.parseInt(String.valueOf(quantidade));
}

From source file:br.luck.contar.MegasenaContar.java

@Override
protected int obterQuantidade(String bola, long concursoinicio, long concursoFim, int colunaInicio,
        int colunaFim) throws Exception {

    List<Long> lista = new ArrayList<Long>();
    long quantidade = 0;

    for (int coluna = colunaInicio; coluna <= colunaFim; coluna++) {
        Criteria criteria = getSession().createCriteria(MegasenaModel.class);
        String col = String.valueOf((coluna < 10) ? "0" + coluna : coluna);

        criteria.setProjection(Projections.count("bola" + col));
        criteria.add(Restrictions.eq("bola" + col, bola));
        criteria.add(Restrictions.between("concurso", concursoinicio, concursoFim));

        try {// w  ww  .  j a  v  a 2  s  .  com
            lista.add((Long) criteria.uniqueResult());
        } catch (Exception e) {
            throw new Exception(e.getMessage());
        }
    }
    // Percorre a lista somando os resultados
    for (Long soma : lista) {
        quantidade = quantidade + soma;
    }
    return Integer.parseInt(String.valueOf(quantidade));
}

From source file:br.ufac.sion.dao.CandidatoFacade.java

@Override
public int contaCandidatos(FiltroCandidatos filtro) {
    Criteria criteria = criarCriteriaParaFiltro(filtro);

    criteria.setProjection(Projections.rowCount());

    return ((Number) criteria.uniqueResult()).intValue();
}