简体   繁体   English

JPA连接继承查询

[英]JPA Joined inheritance query

I'm new to inheritance in JPA. 我是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'. 让我们假设一个连接继承映射,其中A是具有'id'和'name'的实体。 And there are entities A1 and A2 inherited from A. A1 provides the field 'int1', A2 provides the field 'int2' 并且存在从A继承的实体A1和A2。A1提供字段'int1',A2提供字段'int2'

I'd like to use JPQL to get two columns: 'name', 'int' (this one may be 'int1' or 'int2') 我想使用JPQL来获取两列:'name','int'(这可能是'int1'或'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 提前Thnks

You can use UNION. 您可以使用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: 但是很难找到JPQL多态查询的示例,所以这是我的答案:

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 从A a中选择a.int1

That's easy, but I can't find enough docs about the subject. 这很容易,但是我找不到关于该主题的足够文档。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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