Reputation: 23800
So I have this code:
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();
}
I call this code somewhere in my code with
List<FooRequirement> myList = dao.findByFoo(foo);
Then I got a ClassCastException and wondered what I was doing wrong. I debugged my code and I have seen that my list (myList) which is supposed to hold references of type FooRequirement objects is actually filled with references of type Foo.
Then I found my mistake:
return getCurrentSession().createQuery("select distinct fr from FooBarRequirement fr where fr.Foo.id = :FooId"
There was a "select distinct fr.foo" but it should have been a "select distinct fr..." because I want a List of FooRequirements not Foos.
My question is, how did that reference made itself into the List in the first place? I mean how is it possible for a List to hold a foo ?
Some information about the classes:
All of the classes are entities, the db has tables for them.
Foo class has a field id and a description.
FooRequirement class is an ABSTRACT class and has a reference to Foo (ManyToOne), and id. FooRequirement DOES NOT extend Foo.
FooBarRequirement class extends a FooRequirement class, if it is relavent. It has a field Baz. (ManyToOne)
I hope the question is clear. Actually the situation was a bit more complicated but I tried making it as simple as possible.
Upvotes: 0
Views: 144
Reputation: 61548
You are explicitly selecting Foo objects in your query select distinct fr.foo...
So this is the type that ends up in your List
.
EDIT: You have defined the List you want to have as List<FooRequirement>
. However the result list you get from the Session
is not typed and thus can hold any Object
, in your instance - Foo
.
Since you cannot get a TypedQuery
from a Hibernate Session
, you might consider using the EntityManager
interface.
Upvotes: 2