我正在使用單表繼承,一個父物體:
@Entity
@Table(name = "parent")
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "type")
public class Parent {
// ...
}
和兩個子物體:
@Entity
@DiscriminatorValue("child1")
public class Child1 extends Parent {
@Column(name = "child1_property")
private Integer child1Property;
// ...
}
@Entity
@DiscriminatorValue("child2")
public class Child2 extends Parent {
@Column(name = "child2_property")
private Integer child2Property;
// ...
}
Child1現在,如果我直接從物體查詢(HQL) :
from Child1
它將生成一個僅從Parent物體加Child1物體中選擇列的 SQL。如果我使用 a 從Parent物體中選擇where type='child1'
from Parent p where type(p)='child1'
它將僅回傳Child1物體,但 SQL 查詢從 和 中選擇Parent所有Child1列Child2。是否有可能從Parent物體查詢使用鑒別器列(即僅限于Child1物體)并獲得特定的 SQL 查詢,即僅從Parent和中選擇列Child1。
uj5u.com熱心網友回復:
投影似乎有效:
SELECT new fully.qualified.name.of.Child1(p.id, p.name, p.child1Property)
FROM Parent p
WHERE TYPE(p) = 'child1'
生產
select
parent0_.id as col_0_0_,
parent0_.name as col_1_0_,
parent0_.child1_property as col_2_0_
from
parent parent0_
where
parent0_.type='child1'
Hibernate 用戶指南摘錄:
有一個特定的運算式型別只在 select 子句中有效。Hibernate 將此稱為“動態實體化”。JPQL 支持其中的一些功能并將其稱為“建構式運算式”。
因此,我們不是在這里處理 Object[](再次參見 Hibernate Query API),而是將值包裝在一個型別安全的 Java 物件中,該物件將作為查詢結果回傳。
...
投影類在物體查詢中必須是完全限定的,并且它必須定義一個匹配的建構式。
這里的類不需要映射。它可以是 DTO 類。
如果它確實代表一個物體,則結果實體以 NEW 狀態回傳(非托管!)。
但是,我只是SELECT c FROM Child1 c。實際上,我很驚訝 Hibernate 沒有抱怨child1Propertyentity 缺少屬性Parent。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/416764.html
標籤:
