Java Persistence: Cast to something the result of Query.getResultList()


Hey everyone, I'm new to persistence / hibernate and I need your help.

Here's the situation. I have a table that contains some stuff. Let's call them Persons.
I'd like to get all the entries from the database that are in that table.

I have a Person class that is a simple POJO with a property for each column in the table (name, age,..)

Here's what I have :

Query lQuery = myEntityManager.createQuery("from Person")
List<Person> personList = lQuery.getResultList();

However, I get a warning saying that this is an unchecked conversion from List to List<Person>

I thought that simply changing the code to

Query lQuery = myEntityManager.createQuery("from Person")
List<Person> personList = (List<Person>)lQuery.getResultList();

would work.. but it doesn't.

Is there a way to do this ? Does persistence allow me to set the return type of the query ? (Through generics maybe ? )

Best Answer

As a newcomer to JPA was taking this as the definitive answer but then I found a better one via this question: Why in JPA EntityManager queries throw NoResultException but find does not?

Its as simple as as using TypedQuery instead of Query e.g.:

TypedQuery<Person> lQuery = myEntityManager.createQuery("from Person", Person.class);
List<Person> personList = lQuery.getResultList();