在 HQL 查询中使用外连接

发布于 2024-08-13 12:25:37 字数 973 浏览 4 评论 0原文

我正在尝试使用 HQL 和 OUTER JOIN 构建查询,但无法正常工作。考虑以下映射

<class name="Parent">
    <id name="id" type="integer">
      <generator class="native" />
    </id> 
</class>

<class name="Child">
    <id name="id" type="integer">
      <generator class="native" />
    </id> 
    <many-to-one name="parent"/>
</class>

现在我想获得所有父母的列表以及父母的孩子的数量。假设我有一个有两个孩子的父母和一个根本没有孩子的父母。我期望像

+-------------------+
| parent | children |
+--------+----------+
|  1     | 2        |
|  2     | 0        |
+--------+----------+

使用 这样的输出普通 SQL 这根本不是问题,我会得到这个输出,执行类似的操作,

SELECT p.id as parent, count(c.id) as children from parents p LEFT OUTER JOIN children c on c.parent_id = p.id group by p.id;

但是使用 HQL 似乎不可能,因为在使用 a 时需要从父级到子级的路径 OUTER JOIN,我显然没有(也不想添加)

任何关于如何使用 HQL 使查询工作的想法还是真的 - 我简直不敢相信 -缺少休眠功能吗?

I'm trying to build a query using HQL and OUTER JOINs and just can't get it work. Consider the following mapping

<class name="Parent">
    <id name="id" type="integer">
      <generator class="native" />
    </id> 
</class>

<class name="Child">
    <id name="id" type="integer">
      <generator class="native" />
    </id> 
    <many-to-one name="parent"/>
</class>

Now I"d like to get a list of all Parents and the amount of the Parents' children. Suppose I have one Parent with two children and one Parent with no children at all. I'd expect an output like

+-------------------+
| parent | children |
+--------+----------+
|  1     | 2        |
|  2     | 0        |
+--------+----------+

using plain SQL it isn't a problem at all, I'll get this output doing something like

SELECT p.id as parent, count(c.id) as children from parents p LEFT OUTER JOIN children c on c.parent_id = p.id group by p.id;

However it doesn't seem to be possible using HQL as one needs a path from Parent to Child when using a OUTER JOIN, which I obviously don't have (and also don't want to add).

Any ideas how to get the query working using HQL or is it really - I couldn't believe it - a missing hibernate feature?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

白馒头 2024-08-20 12:25:37

切换查询应该有帮助

SELECT p.id as parent, count(c.id) as children from children c right outer join c.parent p group by p.id;

Switching the query should help

SELECT p.id as parent, count(c.id) as children from children c right outer join c.parent p group by p.id;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文