Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ? )

like image 998
GuiSim Avatar asked Jun 05 '09 18:06

GuiSim


People also ask

Which query is executed by list getResultList ()?

getResultList executes the JPQL SELECT statement and returns the results as a List ; if no results are found then it returns an empty list.

Can query return NULL in getResultList?

getResultList() returns an empty list instead of null . So check isEmpty() in the returned result, and continue with the rest of the logic if it is false.

What is hibernate getResultList?

getResultList() Execute a SELECT query and return the query results as an untyped List. java.lang.Object. getSingleResult() Execute a SELECT query that returns a single untyped result.

What is TypedQuery in Java?

public interface TypedQuery<X> extends Query. Interface used to control the execution of typed queries. Since: Java Persistence 2.0 See Also: Query , Parameter.


1 Answers

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(); 
like image 108
Bruce Adams Avatar answered Sep 23 '22 10:09

Bruce Adams