How to make this consultation with JPA?

Asked

Viewed 233 times

1

I would like two solutions to this question, one using a normal typedquery and the other using the criteria due to its great versatility for code.

Here is my query:

      TypedQuery<Pessoa> query = em.createQuery("SELECT a FROM Pessoa a where  
      a.dataNascimento <> '12/9/2000'", Pessoa.class);

how to return this query?

Here is the mistake:

Caused by: java.lang.ClassCastException: java.lang.String cannot be cast to java.time.LocalDate
  • 1

    You yourself have already given the solution with TypedQuery in your question. It means that you only want the solution with Criteria? Or for some reason you also want something more with TypedQuery that is not what you already gave in the question?

  • @Victorstafusa The problem is that when I run this query it gives an error !!

  • Which error? Put the error in the question.

2 answers

2

Try modifying your Where "a. dataNascimento <> '12/9/2000'"

as the equal "="

would look like this: "a. dataNascimento = '12/9/2000' "

//////////////////////////

Well, I guess the problem revolves around the return of the method that contains your query, right? Well, I think this method should solve, using the setParamenter...kkk

public Pessoa buscaDataNasc(String dataNascimento){
        Pessoa pessoa = this.manager.createQuery("select p from Pessoa p where p.dataNascimento = :pDataNascimento")
                .setParameter("pDataNascimento", dataNascimento).getResultList();

        return pessoa;
    }

ps: I don’t have much affinity with the criteria API.

  • I tried to make the same mistake! I think we have to use the . setParameter

  • 1

    tried "a. dataNascimento = '12-09-2000' "?

  • Yes! Remembering that I want to <> and not =

  • vc is right, we have to use .setParameter. Well, I simulated a context similar to this problem and it worked.

  • It is giving error because date is String and not Date. In setParameter passes a Date and not a String. To convert String to Date check here: https://www.mkyong.com/java/how-to-convert-string-to-date-java/

  • It is, taking into account that question did not make clear the type of the data "dataNascimento" and the signature that it treats the variable in the query (12/9/2000), I assumed that it was a String. This is why the method receives the parameter String dataNascimento.

Show 1 more comment

0

It seems the error is in date format...

I had a similar error, the problem is in the search for the format '9/12/2000' which is Brazilian format, and the BD usually works with the international which is '2000-09-12'

Try to search this way... "a. dataNascimento = '2000-09-12' "

  • The issue is not format, but "java.lang.Classcastexception: java.lang.String cannot be cast to java.time.Localdate"

Browser other questions tagged

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