gpt4 book ai didi

hibernate - HQL 右外连接

转载 作者:行者123 更新时间:2023-12-01 16:47:58 25 4
gpt4 key购买 nike

我正在尝试在 HQL 中执行右外连接。查询创建如下所述:

Query query = this.sessionFactory
.getCurrentSession()
.createQuery(
"select
O.customer.id as id,
O.customer.firstName as firstName,
O.customer.lastName as lastName,
O.customer.address as address,
O.customer.city as city,
count(O.id) as totalOrders
from
Order O
right outer join O.customer
group by
O.customer.id");

MySQL 上的 SQL 查询工作正常,但 HQL 查询返回内部连接的结果。

SQL 查询是:

select c.id,
c.firstname,
c.lastname,
c.city,
count(o.id) as total_order
from orders o right outer join customers c
on c.id = o.customer_id group by id

最佳答案

问题在于您编写查询的方式。因为您使用 O.customer.XXXX,Hibernate 在查询中添加了 Order 和 Customer 之间的内部连接以解析 O.customer。您需要通过在右内连接中为 O.customer 引入别名来重写查询以使用右内连接的结果。

select C.id as id, C.firstName as firstName, C.lastName as lastName, 
C.address as address, C.city as city, count(O.id) as totalOrders
from Order O right outer join O.customer C
group by C.id

如果您查看 hibernate 从您的查询中生成的 SQL,您会发现它正在执行内部联接和订单与客户之间的正确内部联接。

关于hibernate - HQL 右外连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18746332/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com