如何在 Hibernate 中以单向多对一方式保留连接表?
我正在利用 如何连接表在单向多对一条件下?。
如果你有两个类:
class A {
@Id
public Long id;
}
class B {
@Id
public Long id;
@ManyToOne
@JoinColumn(name = "parent_id", referencedColumnName = "id")
public A parent;
}
B -> A 是多对一关系。我知道我可以将 B 的集合添加到 A 但我不想要这种关联。
所以我的实际问题是,是否有一种 HQL 或 Criteria 方式来创建 SQL 查询:
select * from A left join B on (b.parent_id = a.id)
这将检索所有 A 记录以及引用 A 的每个 B 记录的笛卡尔积,并且将包括具有以下特征的 A 记录:没有 B 引用它们。
如果您使用:
from A a, B b where b.a = a
那么它是内部联接,并且您不会收到没有 B 引用的 A 记录。
我还没有找到一种无需两个查询即可完成此操作的好方法,因此任何少于此的查询都很好。
谢谢。
I'm piggy-backing off of How to join tables in unidirectional many-to-one condition?.
If you have two classes:
class A {
@Id
public Long id;
}
class B {
@Id
public Long id;
@ManyToOne
@JoinColumn(name = "parent_id", referencedColumnName = "id")
public A parent;
}
B -> A is a many to one relationship. I understand that I could add a Collection of Bs to A however I do not want that association.
So my actual question is, Is there an HQL or Criteria way of creating the SQL query:
select * from A left join B on (b.parent_id = a.id)
This will retrieve all A records with a Cartesian product of each B record that references A and will include A records that have no B referencing them.
If you use:
from A a, B b where b.a = a
then it is an inner join and you do not receive the A records that do not have a B referencing them.
I have not found a good way of doing this without two queries so anything less than that would be great.
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我用您发布的内容做了一个示例,我认为这可能有效:
select a,b from B as b left external join b.parent as a
in HQL。不过,我必须找到一种“标准”方式来做到这一点。
I've made an example with what you posted and I think this may work:
select a,b from B as b left outer join b.parent as a
in HQL.I have to find a "criteria" way of doing that though.
您可以通过指定 fetch 属性来完成此操作。
您可以在以下位置找到它:第 6 章. 集合映射,向下滚动至:6.2。映射集合
编辑
我在您的问题评论中读到您想要一种执行原始 SQL 查询的方法?这里是您可能感兴趣的参考:
第 13 章 - 本机 SQL 查询
如果你想通过 HQL 实现这一点:
第 11 章。 HQL:Hibernate 查询语言
在第 11 章中,您想要向下滚动到11.3。协会和加入。
不过我猜 ClassB 需要是 ClassA 的成员。进一步阅读会有帮助。
另一件可能对您有用的事情是 命名查询:
并从代码中调用此查询,如下所示:
请查看 Ayende 引用的链接,他对此进行了更多解释深入。
You may do so by specifying the fetch attribute.
You find it at: Chapter 6. Collection Mapping, scroll down to: 6.2. Mapping a Collection
EDIT
I read in your question's comment that you wanted a way to perform a raw SQL query? Here a reference that might possibly be of interest:
Chapter 13 - Native SQL Queries
and if you want a way to make it possible through HQL:
Chapter 11. HQL: The Hibernate Query Language
In chapter 11, you want to scroll down to 11.3. Associations and joins.
I guess however that ClassB needs to be a member of ClassA. Further reasdings shall help.
Another thing that might proove to be useful to you are named queries:
And calling this query from within code like so:
Please take a look at the referenced link by Ayende who explains it more in depth.