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

I have two tables, a DVD and a contact.

DVDs can be rented to contact, and many DVDs can be rented by contact.

Much in one link (dvd-->contact) works great.

But another way fails: (contact-->dvd)

This is a contact mapping:

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

Here is the setter getter used for the 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 a DVD taken out of 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 to fix it?

Edit: this solved my problem:

 .setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY) 
+4
source share
4 answers

You do not need to specify a HashSet . This is Set , and it does not provide any additional methods. So just don't drop it.

This is a general rule when working with collections - do not refer to them with their specific classes (unless you really need to). Use List and Set , not ArrayList and HashSet

+14
source

Do not try to use Set dds in a HashSet . Hibernate uses its own implementation of the Set interface called PersistentSet , which is not the result of a HashSet , and therefore casting throws a ClassCastException . Either use it through the Set interface, or create a new HashSet using your constructor (in this case, your changes to the set will not be automatically displayed in Hibernate).

 Set<Dvd> tt = dds; 

OR

 HashSet<Dvd> tt = new HashSet<Dvd>(dds); 
+4
source

Abhinav Sarkar's answer is , of course, correct, but there is also a mistake in your modeling.

The relationship between a DVD and a contact is many-to-many, not many-to-one (otherwise each DVD will be unique to one client)

+1
source

I recently ran into this problem. I was able to eradicate the problem of casting.

List<Object> listObject = Arrays.asList(ListFromHibernate.toArray());

Then you can get the objects by selecting the objects in the list, say.

MyObject x = (MyObject) listObject.get(1);

PS: It excites 2013.

+1
source

Source: https://habr.com/ru/post/1334061/


All Articles