我正在尝试在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
答案 0 :(得分:7)
问题在于您编写查询的方式。因为您使用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
如果您要查看从查询中生成的休眠SQL,您会看到它正在执行两者内部联接和订单与客户之间的右内联接。