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

License:Open Source License

/**
 * //from   w w w . java 2  s.c  o  m
 * @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

/**
 * /*from  w  w  w.  jav a2s  .  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 ww  .j  av a2 s.c  om*/
    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 w w . ja  va2  s  .  co m*/

    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.jfrj.siga.hibernate.ExDao.java

License:Open Source License

public void listarNaoIndexados(int aPartir, boolean irIndexando) throws Exception {

    long tempoIni = System.currentTimeMillis();
    FullTextSession fullTextSession = Search.getFullTextSession(getSessao());
    QueryParser parser = new QueryParser(Version.LUCENE_36, "idDoc", new StandardAnalyzer(Version.LUCENE_36));

    final Criteria crit = getSessao().createCriteria(ExDocumento.class)
            .add(Restrictions.gt("idDoc", new Long(aPartir)));
    crit.setMaxResults(300);//ww w.java 2  s  . c  o m
    crit.addOrder(Order.asc("idDoc"));
    List<ExDocumento> list = new ArrayList<ExDocumento>();
    int firstResult = 0;
    do {
        crit.setFirstResult(firstResult);
        list = crit.list();
        for (ExDocumento doc : list) {
            firstResult++;
            if (doc.isIndexavel() && (fullTextSession
                    .createFullTextQuery(new TermQuery(new Term("idDoc", String.valueOf(doc.getIdDoc()))),
                            ExDocumento.class)
                    .getResultSize() == 0)) {

                if (irIndexando) {
                    System.out.println("listarNaoIndexados - indexando " + doc.getCodigo());
                    indexar(doc);
                } else {
                    System.out.println("listarNaoIndexados - nao indexar " + doc.getCodigo());
                }
            }
        }
        System.out.println("listarNaoIndexados - " + firstResult + " varridos");
        getSessao().clear();
    } while (list.size() > 0);
    System.out.println(
            "listarNaoIndexados - FIM    " + (System.currentTimeMillis() - tempoIni) / 3600000 + " minutos");
}

From source file:br.gov.jfrj.siga.hibernate.ExDao.java

License:Open Source License

public void indexarTudo(Aguarde aguarde) throws Exception {

    System.out.println("Indexando documentos...");
    long inicio = new Date().getTime();

    try {//from   w ww  . j  a  v  a  2s  . co m
        FullTextSession fullTextSession = Search.getFullTextSession(getSessao());
        Transaction deleteTx = fullTextSession.beginTransaction();
        fullTextSession.purgeAll(ExDocumento.class);
        deleteTx.commit();
        fullTextSession.clear();
        getSessao().clear();
    } catch (Throwable t) {
        // No havia documentos a excluir
    }

    final Criteria crit = getSessao().createCriteria(ExDocumento.class);

    int index = 0;

    FullTextSession fullTextSession = Search.getFullTextSession(getSessao());
    fullTextSession.setFlushMode(FlushMode.MANUAL);
    fullTextSession.setCacheMode(CacheMode.IGNORE);
    crit.setMaxResults(30);
    crit.addOrder(Order.desc("idDoc"));
    List<ExDocumento> list;
    do {
        crit.setFirstResult(index);
        list = crit.list();
        Transaction tx = fullTextSession.beginTransaction();
        for (ExDocumento doc : list) {
            index++;
            // if (aguarde != null)
            // aguarde.setMensagem(String.valueOf(index)
            // + " documentos j indexados.");
            if (doc.isIndexavel())
                fullTextSession.index(doc);

            if (index % 100 == 0) {
                //System.gc();
                // fullTextSession.flush();
                // fullTextSession.clear();
            }
        }
        tx.commit();
        fullTextSession.clear();
        getSessao().clear();
        System.out.print(String.valueOf(index) + " documentos j indexados. --  -- ");
    } while (list.size() > 0);
    //System.gc();

    // fullTextSession.close();
    System.out.println("Durao da indexao de documentos: " + (new Date().getTime() - inicio));

    if (aguarde != null)
        aguarde.setMensagem(String.valueOf(index));

}

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

@Override
public List<Candidato> buscaTodosComPaginacao(FiltroCandidatos filtro) {
    Criteria criteria = criarCriteriaParaFiltro(filtro);

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

    return criteria.list();
}

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

@Override
public List<Cidade> buscaTodosComPaginacao(FiltroCidades filtro) {
    Criteria criteria = criarCriteriaParaFiltro(filtro);

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

    return criteria.list();
}

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

@Override
public List<Inscricao> findByConcurso(FiltroInscritos filtro) {
    Criteria criteria = criarCriteriaParaFiltro(filtro);

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

    return criteria.list();
}

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

@Override
public List<Inscricao> findByConcursoAndConfirmadasESubJudice(FiltroInscritos filtro) {

    Criteria criteria = criarCriteriaParaFiltro(filtro);

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

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

    return criteria.list();
}