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