Java,Hibernate java.lang.ClassCastException:org.hibernate.collection.PersistentSet不能转换为java.util.HashSet [英] Java, Hibernate java.lang.ClassCastException: org.hibernate.collection.PersistentSet cannot be cast to java.util.HashSet
问题描述
我有两张桌子,DVD和联系人。
一张DVD可以租给一个联系人,一个联系人可以租借许多DVD。
多对一链接(dvd - >联系人)
可以正常工作。
但另一种方式失败:(contact - > dvd)
这是联系人映射:
< set name =dvdsinverse =true>
< key column =contactId/>
<一对多课程=Dvd/>
< / set>
这里是联系人的setter getter:
私人设定< Dvd> dvds = new HashSet< Dvd>();
public Set< Dvd> getDvds(){
return dvds;
}
public void setDvds(Set< Dvd> dvds){
this.dvds = dvds;
}
当我尝试从这个联系人租借DVD时:
HashSet< Dvd> tt =(HashSet< Dvd>)dds;
我得到一个例外:
java.lang.ClassCastException:org.hibernate.collection.PersistentSet
不能转换为java.util.HashSet
Exception是什么意思,我该如何解决它?
编辑:这解决了我的问题:
.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY)
您不需要转换为 HashSet
。它是一个 Set
,它不提供任何其他方法。所以只是不要投。
这是处理集合时的一个通用规则 - 不要用它们的具体类引用它们(除非真的需要)。使用 List
和 Set
,而不是 ArrayList
和 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)
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
这篇关于Java,Hibernate java.lang.ClassCastException:org.hibernate.collection.PersistentSet不能转换为java.util.HashSet的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!