休眠-> ArrayList 无法转换为 Set
我有一个 Java EE 应用程序,并且使用 Hibernate。域对象,我将List / ArrayList更改为Set / HashSet,因为使用Sets更好。
但是在我的 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;
}
这里我得到一个错误:
java.lang.ClassCastException: java.util.ArrayList cannot be cast to java.util.Set
我该怎么做才能避免这个错误?
预先感谢您&此致。
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.
But in my Dao implementation I run into a problem:
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
sess.createQuery("from Item").list();
将返回结果项的数组列表,如果您在 Set 中需要它,可以按照代码所示进行制作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使用
Set
并不是“更好”,它完全取决于您的需要。但无论如何,您在域对象中使用的集合类型以及Query#list()
是两个不相关的事物。就我个人而言,我不能说我认为将查询结果转换为
Set
有多大价值(除了占用更多内存),除非您明确想要删除 当然是查询结果的重复项(但在这种情况下,我会质疑映射)。现在,如果您坚持的话,各种
Set
实现都有一个采用Collection
的构造函数(并且问题本质上是 将列表转换为集合的最简单方法? - Java)。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 ofQuery#list()
are two unrelated things.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 results of course (but in that case, I would challenge the mappings).Now, if you insist, the various
Set
implementations have a constructor that takes aCollection
(and the question is essentially a duplicate of Easiest way to convert a List to a Set? - Java).