java getresultlist,Java Persistence:转换为Query.getResultList()的结果的东西?

  • Post author:
  • Post category:java


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 personList = lQuery.getResultList();

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

I thought that simply changing the code to

Query lQuery = myEntityManager.createQuery(“from Person”)

List personList = (List)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 ? )

解决方案

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 lQuery = myEntityManager.createQuery(“from Person”, Person.class);

List personList = lQuery.getResultList();