Hibernate -> ArrayList cannot be cast to Set

这一生的挚爱 提交于 2019-12-12 08:31:01

问题


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.


回答1:


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




回答2:


The domain objects, I changed the List / ArrayList to Set / HashSet, because it is better to use 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.

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 a Collection (and the question is essentially a duplicate of Easiest way to convert a List to a Set? - Java).



来源:https://stackoverflow.com/questions/3914390/hibernate-arraylist-cannot-be-cast-to-set

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!