简体   繁体   中英

I can't downcast in JPQL/Hibernate - Unable to find domain.Scoreable with id 16

I have an abstract class called Scoreable and it's extended by two classes named Idea and Solution . That is, both subclasses may have a set of scores. Every Score has a field scoreable that is a FK.

What I want to get is a collection of Scores given, for example, an Idea. So I've tried the following query:

select s from Score s join s.scoreable idea where idea.id = 16;

But it returns Unable to find domain.Scoreable with id 16 , maybe because the Scoreable table doesn't exist in the database. Also I tried a downcast with this query select s from Score s join TREAT(s.scoreable AS Idea) idea where idea.id = 16; . In this case, I get the same response.

Your problem may be because you mapped the Scorable with @MapedSuperclass and now you want to include the base type in a query. For this you need the base class to be an actual @Entity instead.

According to the JPA documentation:

A mapped superclass is a non-entity class that can define persistent state and mapping information for entity subclasses. Mapped superclasses are usually abstract. Unlike true entities, you cannot query a mapped superclass, pass a mapped superclass instance to any EntityManager or Query methods, or declare a persistent relation with a mapped superclass target. You denote a mapped superclass with the MappedSuperclass marker annotation.

So you can have Scorable as both the base class and an @Entity, while its subclases idea dn Solution are @Entities too.For more about this inheritance model, check this JPA example from Oracle .

If you only need Idea's scores you can issue the following query:

select distinct s 
from Idea i
join i.scores s
where i.id = ?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM