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

笑着哭i 提交于 2019-11-30 02:52:21
Bruce Adams

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();
Henning

Note: This answer is outdated as of JPA 2.0, which allows you to specify the expected type. See this answer.


Suppressing the warning with

@SuppressWarnings("unchecked")
List<MyType> result = (List<MyType>) query.getResultList();

is the only solution to this problem I have ever seen. The suppression is ugly, but you can trust JPA to return the right type of object, so there is no need to check manually.

If you use polymorphisms and don't know the exact result type, the use of Generics with a bounded Class parameter is also a common pattern:

public List<T extends MyBaseType> findMyType(Class<T> type) {
    @SuppressWarnings("unchecked")
    List<T> result = (List<T>) this.entityManager.createQuery(
        "FROM " + type.getName())
        .getResultList();
    return result;
}

Well there is the java Collections class solution, but you didn't explain how your casting was failing, or if it was just giving a warning...

This is one way to validate this:

Collections.checkList(lQuery.getResultList(), Person.class);

But if you don't need to validate it:

@SuppressWarnings("unchecked") List<Person> personList = lQuery.getResultList();

I've been stuck with this problem for a while, too. You can iterate over the list, and check, but I'd prefer less noise. The shortest way I have seen getting around this is to silence the warning, but I am also very uncomfortable with that. I'd be interested to see other solutions.

@SuppressWarnings("unchecked") 
List<Person> personList = lQuery.getResultList();

Hmm, while researching I found an interesting post on java.net. I found the user comments particularly interesting.

Alternative way:

Query query = entityManager.createNativeQuery("SELECT * FROM person", Person.class);
List<Person> rows = query.getResultList();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!