Hibernate Criteria API - 创建自动连接
我有以下设置
Seizure {
private SeizureI18n seizureI18n;
@OneToOne(fetch = FetchType.LAZY)
@PrimaryKeyJoinColumn
public SeizureI18n getSeizureI18n() {
return this.seizureI18n;
}
}
SeizureI18n {
private Seizure seizure;
@OneToOne(fetch = FetchType.LAZY, mappedBy = "seizureI18n")
public Seizure getSeizure() {
return this.seizure;
}
}
当我使用以下 Criteria
查询发出查询(观察别名的使用情况)时,
criteria = metaDataConsole.session.createCriteria(Seizure.class,"Seizure");
criteria.createCriteria("Seizure.seizureI18n");
criteria.list();
它会生成以下 SQL 查询。
FROM incbszdb.seizure this_
INNER JOIN incbszdb.seizure_i18n seizurei18x1_
ON this_.id = seizurei18x1_.id
LEFT OUTER JOIN incbszdb.seizure seizure4_
ON seizurei18x1_.id = seizure4_.id
第二次癫痫发作
LEFT OUTER JOIN incbszdb.seizure seizure4_
ON seizurei18x1_.id = seizure4_.id
来自哪里?
I have the following setup
Seizure {
private SeizureI18n seizureI18n;
@OneToOne(fetch = FetchType.LAZY)
@PrimaryKeyJoinColumn
public SeizureI18n getSeizureI18n() {
return this.seizureI18n;
}
}
SeizureI18n {
private Seizure seizure;
@OneToOne(fetch = FetchType.LAZY, mappedBy = "seizureI18n")
public Seizure getSeizure() {
return this.seizure;
}
}
When I issue a query with the following Criteria
query (observe the usage of an alias)
criteria = metaDataConsole.session.createCriteria(Seizure.class,"Seizure");
criteria.createCriteria("Seizure.seizureI18n");
criteria.list();
it results in the following SQL query.
FROM incbszdb.seizure this_
INNER JOIN incbszdb.seizure_i18n seizurei18x1_
ON this_.id = seizurei18x1_.id
LEFT OUTER JOIN incbszdb.seizure seizure4_
ON seizurei18x1_.id = seizure4_.id
Where does the second join to seizures
LEFT OUTER JOIN incbszdb.seizure seizure4_
ON seizurei18x1_.id = seizure4_.id
comes from?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为 Hibernate 添加此连接是因为,在加载 SeizureI18n 时,它无法知道 SeizureI18n 是否具有关联的 Seizure。因此,无法知道他是否必须用 null 或 Seizure 实例(或 Seizure 实例的代理)填充 Seizure 字段。当然,在这个特定的查询中,这似乎很奇怪。但如果你只是加载 SeizureI18n 而没有 Seizure,那感觉会更正常。
如果 SeizureI18n 始终具有关联的 Seizure,则应将关联标记为非可选 (
可选 = false
)。我认为它应该避免额外的连接(因为 Hibernate 知道存在关联的 Seizure,因此该属性永远不会为空)。I think Hibernate adds this join because, when loading a SeizureI18n, it's unable to know if the SeizureI18n has an associated Seizure or not. So it's unable to know if he must populate the seizure field with null or with a Seizure instance (or proxy to a Seizure instance). Of course, in this particular query, it seems strange. But if you were just loading SeizureI18n without their Seizure, it would feel more normal.
If a SeizureI18n always has an associated Seizure, you should mark the association as non-optional (
optional = false
). I think it should avoid the additional join (since Hibernate would know that there is an associated Seizure, and that the property is thus never null).