[英]Hibernate class cast exception with Lists
所以我有這個代碼:
public List<FooRequirement> findByFoo(Foo foo) {
return getCurrentSession().createQuery("select distinct fr.foo from FooBarRequirement fr where fr.Foo.id = :FooId")
.setParameter("FooId", foo.getId()).list();
}
我在代碼中的某個地方調用了這段代碼
List<FooRequirement> myList = dao.findByFoo(foo);
然后我得到了一個ClassCastException,並想知道我做錯了什么。 我調試了我的代碼,我看到我的列表(myList)應該包含類型為FooRequirement對象的引用實際上填充了類型為Foo的引用。
然后我發現了我的錯誤:
return getCurrentSession().createQuery("select distinct fr from FooBarRequirement fr where fr.Foo.id = :FooId"
有一個“選擇不同的fr.foo”,但它應該是一個“選擇不同的fr ...”因為我想要一個FooRequirements列表而不是Foos。
我的問題是,該引用是如何首先進入列表的? 我的意思是List怎么可能舉行foo?
有關課程的一些信息:
所有類都是實體,db有表。
Foo類有一個字段ID和描述。
FooRequirement類是一個ABSTRACT類,它引用了Foo(ManyToOne)和id。 FooRequirement不會擴展Foo。
如果它是相關的,FooBarRequirement類擴展了一個FooRequirement類。 它有一個字段Baz。 (多對一)
我希望這個問題很清楚。 實際上情況有點復雜但我盡量讓它盡可能簡單。
您在查詢中明確選擇Foo對象select distinct fr.foo...
所以這是最終列在你的List
的類型。
編輯:您已將List想要的列表定義為List<FooRequirement>
。 但是,您從Session
獲得的結果列表不是鍵入的,因此可以在您的實例中保存任何Object
- Foo
。
由於您無法從Hibernate Session
獲取TypedQuery
,因此您可以考慮使用EntityManager
接口 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.