Help on a JPA query

Asked

Viewed 85 times

0

I’m trying to make a query using JPA criteria, it would be as follows:

I will pass 2 Start date and a Final Date and a vehicle plate how can I make this query?

NOTE: The table that I will consult would be Servico and it has a Car where this car would have a plate, I believe that up to this point is correct.

public List<Servico> buscarServicoDeVeiculoEntreDatas(Date diaServico, Date diaGarantia, Carro carro) {

        CriteriaBuilder builder = manager.getCriteriaBuilder();
        CriteriaQuery<Servico> criteriaQuery = builder.createQuery(Servico.class);

        Root<Servico> s = criteriaQuery.from(Servico.class);
        criteriaQuery.select(s);

1 answer

0

        ParameterExpression<Date> dataInicial = builder.parameter(Date.class, "dataInicial");
        ParameterExpression<Date> dataFinal = builder.parameter(Date.class, "dataFinal");

    criteriaQuery.where(builder.between(s.get("data"), dataInicial, dataFinal));

    TypedQuery<Servico> query = manager.createQuery(criteriaQuery);

        Calendar dataIni = Calendar.getInstance();
        dataIni.setTime(Seta sua data aqui);
        dataIni.set(Calendar.HOUR_OF_DAY, 0);
        dataIni.set(Calendar.MINUTE, 0);
        dataIni.set(Calendar.SECOND, 0);

        Calendar dataFin = Calendar.getInstance();
        dataFin.setTime(Seta sua data aqui);
        dataFin.set(Calendar.HOUR_OF_DAY, 23);
        dataFin.set(Calendar.MINUTE, 59);
        dataFin.set(Calendar.SECOND, 59);

        query.setParameter("dataInicial", dataIni.getTime());
        query.setParameter("dataFinal", dataFin.getTime());


    return query.getResultList();

Add this snippet to the end and adapt to your project.

  • in this setTime method what I put in the parameter? NOTE: I want to search by date and not by Time.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.