10

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
  • 3
    Are you sure that you know what the difference between a set and a list is? Because in no way is it 'better' to use a Set. You use Sets whenever you want a single instance of an object in your collection, whereas you can have multiple instances of the same object in a list. Commented Oct 12, 2010 at 12:06

2 Answers 2

25
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

Sign up to request clarification or add additional context in comments.

4 Comments

or rebuild the database which might not be an option
minor issue, it should be Set<Item> items = new HashSet<Item>(list);. Apart from that: +1
"rebuild the database which might not be an option" - This makes no sense, Query.list() always returns a List: docs.jboss.org/hibernate/stable/core/javadoc/org/hibernate/…
@mattb the link is broken.
3

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

1 Comment

When I need help with JPA/HSQL you are nowhere to be seen, but you appear! outrageous :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.