简体   繁体   中英

JPA Joined inheritance query

I'm new to inheritance in JPA. I dont know how to query something like this:

Let's suppose a joined inheritance mapping where A is an entity with 'id' and 'name'. And there are entities A1 and A2 inherited from A. A1 provides the field 'int1', A2 provides the field 'int2'

I'd like to use JPQL to get two columns: 'name', 'int' (this one may be 'int1' or 'int2')

I want to do something like that:

select a.name,
  case type(a)
    when A1 a1 then a1.int1
    when A2 a2 then a2.int2
  end as int 
from A a

But obviously it does not work, how can I make this query? I'm using hibernate implementation.

I need to preserve pagination and, if possible, ordering, I think that may be better to change from "joined" to "single table", does it make any sense?

Thnks in advance

You can use UNION.

select a1.name as name, a1.int1 as id
from A1 a1
UNION
select a2.name as name, a2.int2 as id
from A2 a2

It was so simple! But is hard to find examples of JPQL polymorphic queries, so here is my answer:

select a.name,
case type (a)
  when (A1) then a.int1 
  when (A2) then a.int2
end
from A a

The common way to get a field of a child entity is to query directly the child field name, ie:

select a.int1 from A a

That's easy, but I can't find enough docs about the subject.

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