Java 持久性:将 Query.getResultList() 的结果转换为某些内容?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/957394/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 21:34:40  来源:igfitidea点击:

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

javahibernatecastingpersistence

提问by GuiSim

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,..)

我有一个 Person 类,它是一个简单的 POJO,表中的每一列都有一个属性(名称、年龄等)

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 Listto List<Person>

但是,我收到一条警告,说这是从List到的未经检查的转换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 ? )

有没有办法做到这一点 ?持久性是否允许我设置查询的返回类型?(也许通过泛型?)

采纳答案by 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?

作为 JPA 的新手,我将此作为最终答案,但后来我通过这个问题找到了一个更好的答案:Why in JPA EntityManager queries throw NoResultException but find not?

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

它就像使用 TypedQuery 而不是 Query 一样简单,例如:

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

回答by Charlie

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 poston java.net. I found the user comments particularly interesting.

嗯,在研究时我在 java.net 上发现了一个有趣的帖子。我发现用户评论特别有趣。

回答by Petriborg

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...

好吧,有 java Collections 类解决方案,但是您没有解释您的转换是如何失败的,或者它是否只是发出警告...

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

回答by Henning

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

注意:此答案自 JPA 2.0 起已过时,它允许您指定预期类型。看到这个答案



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.

是我见过的这个问题的唯一解决方案。抑制是丑陋的,但您可以信任 JPA 返回正确类型的对象,因此无需手动检查。

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

如果您使用多态并且不知道确切的结果类型,则使用具有有界Class参数的泛型也是一种常见模式:

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;
}

回答by ukchaudhary

Alternative way:

替代方式:

Query query = entityManager.createNativeQuery("SELECT * FROM person", Person.class);
List<Person> rows = query.getResultList();