[英]Hibernate HQL strange behavior with IS NULL
我有一個HQL查詢的問題。 我希望將管理性別設置為“M”或沒有管理性的所有PID(在Java中將值設置為null)。
PID.class
@Entity
@Table(name = "PatientIdentification")
public class PID {
@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "administrativeSex", referencedColumnName = "is_id")
private IS administrativeSex;
...
}
IS.class
@Entity
@Table(name = "CodedValueForUserDefinedTables")
public class IS {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "is_id")
private Integer id;
private String value;
...
}
HQL查詢
from PID where administrativeSex is null or administrativeSex.value = 'M'
生成的SQL
select
pid0_.pid_id as pid1_84_,
pid0_.administrativeSex as adminis11_84_,
pid0_.birthOrder as birthOrder84_,
pid0_.birthPlace as birthPlace84_,
pid0_.citizenship as citizen12_84_,
pid0_.countyCode as countyCode84_,
pid0_.dateTimeOfBirth as dateTim19_84_,
pid0_.driverLicenseNumber as driverL22_84_,
pid0_.maritalStatus as maritalS8_84_,
pid0_.multipleBirthIndicator as multiple4_84_,
pid0_.nationality as nationa17_84_,
pid0_.owner_id as owner9_84_,
pid0_.patientAccountNumber as patientA6_84_,
pid0_.patientDeathDateAndTime as patient16_84_,
pid0_.patientDeathIndicator as patient18_84_,
pid0_.patientId as patientId84_,
pid0_.primaryLanguage as primaryL7_84_,
pid0_.race as race84_,
pid0_.religion as religion84_,
pid0_.setId as setId84_,
pid0_.ssnNumber as ssnNumber84_,
pid0_.veteransMilitaryStatus as veterans2_84_
from
PatientIdentification pid0_,
CodedValueForUserDefinedTables is1_
where
pid0_.administrativeSex=is1_.is_id
and (
pid0_.administrativeSex is null
or is1_.value='M'
)
該查詢僅返回管理性別設置為“M”的PID。 它缺少一個沒有行政性的人。 如果查看SQL查詢,這是正常的。 如何更正我的HQL查詢?
hibernate參考手冊寫道 :
HQL支持兩種形式的關聯連接:隱式和顯式。
上一節中顯示的查詢都使用顯式形式,即在from子句中顯式使用join關鍵字的位置。 這是推薦的表格。
隱式表單不使用join關鍵字。 相反,使用點符號“解除引用”關聯。 隱式連接可以出現在任何HQL子句中。 隱式連接導致生成的SQL語句中的內部聯接。
由於內部聯接過濾掉了連接條件不匹配的行,因此您缺少未知性別的人。 您將需要一個左外連接,您必須要求明確 :
from PID pid
left outer join pid.administrativeSex as sex
where pid.administrativeSex is null or sex.value = 'M'
看起來你正在做一個內連接。
from
PatientIdentification pid0_,
CodedValueForUserDefinedTables is1_
where
pid0_.administrativeSex=is1_.is_id
除非在CodedValueForUserDefinedTables中有一個條目,其中is_id也為null,否則不會返回administrativeSex為null的任何值。
我發現OneToOne映射很難處理。 您是否考慮過使用@SecondaryTable
注釋嘗試將字符串值映射為頂級類中的字段?
您是否考慮過直接使用外部聯接?
from PID p left join p.administrativeSex with value = 'M'
希望有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.