Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java, Hibernate java.lang.ClassCastException: org.hibernate.collection.PersistentSet cannot be cast to java.util.HashSet

I have two tables, DVD and Contact.

A DVD can be rented to a contact and a contact can rent many DVD's.

The many to one link (dvd-->contact) works fine.

But the other way fails: (contact-->dvd)

This is the contact mapping:

<set name="dvds" inverse="true">
   <key column="contactId"/>
   <one-to-many class="Dvd"/>
</set>

Here is setter getter for Contact:

private Set<Dvd> dvds = new HashSet<Dvd>();

public Set<Dvd> getDvds(){
   return dvds;
}
public void setDvds(Set<Dvd> dvds){
   this.dvds=dvds;
}

When I try to get the DVD rented from a contact with this:

HashSet<Dvd> tt = (HashSet<Dvd>)dds;

I get an Exception:

java.lang.ClassCastException: org.hibernate.collection.PersistentSet 
cannot be cast to java.util.HashSet

What does the Exception mean and how do I fix it?

Edit: This solved my problem:

.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY)
like image 494
gaymer Avatar asked Jan 03 '11 12:01

gaymer


2 Answers

You don't need to cast to HashSet. It is a Set, and it does not provide any additional methods. So just don't cast.

This is a general rule when working with collections - don't refer to them with their concrete classes (unless you really need to). Use List and Set, rather than ArrayList and HashSet

like image 159
Bozho Avatar answered Nov 15 '22 06:11

Bozho


Don't try to cast the Set dds into HashSet. Hibernate uses its own implementation of the Set interface called PersistentSet which does not derive from HashSet and hence the casting throws a ClassCastException. Either use it through the Set interface, or create a new HashSet using its constructor (in which case your changes to the set will not be reflected in Hibernate automatically).

Set<Dvd> tt = dds;

OR

HashSet<Dvd> tt = new HashSet<Dvd>(dds);
like image 28
Abhinav Sarkar Avatar answered Nov 15 '22 08:11

Abhinav Sarkar