我有这个测试 HQL:
select distinct o from Order o left join fetch o.lineItems
它确实在没有明显原因的情况下生成了一个不同的 SQL:
select distinct order0_.id as id61_0_, orderline1_.order_id as order1_62_1_...
SQL 结果集始终相同(有和没有 SQL 不同):
order id | order name | orderline id | orderline name
---------+------------+--------------+---------------
1 | foo | 1 | foo item
1 | foo | 2 | bar item
1 | foo | 3 | test item
2 | empty | NULL | NULL
3 | bar | 4 | qwerty item
3 | bar | 5 | asdfgh item
为什么 hibernate 会生成不同的 SQL? SQL distinct 没有任何意义,并使查询比所需的更慢。
这与FAQ相反其中提到在这种情况下 hql distinct 只是结果转换器的快捷方式:
session.createQuery("select distinct o from Order o left join fetch o.lineItems").list();
It looks like you are using the SQL DISTINCT keyword here. Of course, this is not SQL, this is HQL. This distinct is just a shortcut for the result transformer, in this case. Yes, in other cases an HQL distinct will translate straight into a SQL DISTINCT. Not in this case: you can not filter out duplicates at the SQL level, the very nature of a product/join forbids this - you want the duplicates or you don't get all the data you need.
谢谢
最佳答案
仔细查看 hibernate 生成的 sql 语句 - 是的,它确实使用了“distinct”关键字,但不是我认为您期望的方式(或 Hibernate FAQ 暗示的方式),即返回一组“独特”或“独特”的命令。
它不使用 distinct 关键字来返回不同的订单,因为考虑到您还指定的连接,这在该 SQL 查询中没有意义。
生成的 sql 集仍然需要由 ResultTransformer 处理,因为很明显 sql 集包含重复的订单。这就是为什么他们说 HQL distinct 关键字不直接映射到 SQL distinct 关键字的原因。
关于sql - 为什么 hibernate hql distinct 会导致 sql 在左连接中不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5471819/