Java Hibernate -> ArrayList 不能转换为 Set

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3914390/
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-14 06:48:05  来源:igfitidea点击:

Hibernate -> ArrayList cannot be cast to Set

javahibernatearraylistsetclasscastexception

提问by Tim

I have a Java EE application and I use Hibernate. The domain objects, I changed the List / ArrayList to Set / HashSet, because it is better to use Sets.

我有一个 Java EE 应用程序,我使用 Hibernate。域对象,我把List/ArrayList改成了Set/HashSet,因为用Sets比较好。

But in my Dao implementation I run into a problem:

但是在我的 Dao 实现中,我遇到了一个问题:

public Set<Person> getAllPersons() {
    SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
    Session sess = sessionFactory.getCurrentSession();

    Transaction tx = sess.beginTransaction();
    @SuppressWarnings("unchecked")
    Set<Item> items = (Set<Item>) sess.createQuery("from Item").list();
    tx.commit();

    return items;
}

Here I get an error:

在这里我得到一个错误:

java.lang.ClassCastException: java.util.ArrayList cannot be cast to java.util.Set

What can I do to avoid this error?

我该怎么做才能避免这个错误?

Thank you in advance & Best Regards.

提前致谢并致以最诚挚的问候。

采纳答案by Jigar Joshi

List<Item> list = sess.createQuery("from Item").list();
Set<Item> items = new HashSet<Item>(list);  

sess.createQuery("from Item").list();will return a array list of resulting items, if you need it in Set you can make it as shown in code

sess.createQuery("from Item").list();将返回结果项的数组列表,如果您在 Set 中需要它,您可以按照代码所示进行设置

回答by Pascal Thivent

The domain objects, I changed the List / ArrayList to Set / HashSet, because it is better to use Sets.

域对象,我把List/ArrayList改成了Set/HashSet,因为用Sets比较好。

It's not "better" to use Set, it depends entirely on what you need. But anyway, the collection type you use in your domain objects and the return type of Query#list()are two unrelated things.

使用并不是“更好” Set,这完全取决于您的需要。但无论如何,你在域对象中使用的集合类型和返回类型Query#list()两个不相关的东西

Personally, I can't say that I see much value in converting the result of a query into a Set(apart from eating more memory), unless you explicitly want to remove duplicates from query resultsof course (but in that case, I would challenge the mappings).

就我个人而言,我不能说我认为将查询结果转换为 a Set(除了占用更多内存)有多大价值,除非您当然想从查询结果中删除重复项(但在这种情况下,我会挑战映射)。

Now, if you insist, the various Setimplementations have a constructor that takes a Collection(and the question is essentially a duplicate of Easiest way to convert a List to a Set? - Java).

现在,如果您坚持,各种Set实现都有一个采用 a 的构造函数Collection(问题本质上是将 List 转换为 Set最简单方法的重复? - Java)。