EBG
EBG

Reputation: 51

Cast an Object wtih different classes inside

I´m triying to cast an object that comes from two differents classes. I get the object from a HQL query like this:

select F.title, F.length, F.specialFeatures 
from Film F 
left join F.filmActors X 
inner join X.actor A 
where A.firstName like 'E%'

The object gets part from Actors, Film and FilmActors. The problem appears when I try to cast the object:

Film fl = (Film) o;

And shows this error:

java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to sakila.entity.Film
at Formulario_AD04.mostrarResultados(Formulario_AD04.java:76)

How can I cast the object if it comes from sakila.entity.film, sakila.entity.Actor, etc...?

Upvotes: 0

Views: 48

Answers (1)

Vole Rig
Vole Rig

Reputation: 11

You need to better understand what is the type of the result list from an hibernate query.list() method.

This is a List<Film> where Film is a hibernate entity if the query projection is simple like :

select F from Film F

But in your case, your projection is

select S1, S2, S2

where S1, S2 and S3 are three scalars (according to the query defined in consultaActor)

So the actual type of the output list is List<Object[]> hence the error java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to sakila.entity.Film where you try to cast an Object[] to a Film, which is illegal.

Upvotes: 1

Related Questions