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 ? )
getResultList executes the JPQL SELECT statement and returns the results as a List ; if no results are found then it returns an empty list.
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.
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.
public interface TypedQuery<X> extends Query. Interface used to control the execution of typed queries. Since: Java Persistence 2.0 See Also: Query , Parameter.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With