【问题标题】:Query failing unless I reorder the values in SELECT statement查询失败,除非我重新排序 SELECT 语句中的值
【发布时间】:2016-01-21 22:33:18
【问题描述】:

我正在尝试进行 HQL 查询,但我不明白如果我不对 SELECT 语句中的值重新排序,为什么查询会失败

以下查询不起作用

查询 1

@Query("SELECT uf.flight.arrivalAirport.iataCode, uf.flight.flightStatus " +
        "FROM UserFlight uf WHERE uf.flight.id=?1 AND uf.user.id=?2")

生成的 SQL

select airport2_.iata_code as col_0_0_, 
flight1_.flight_status_id as col_1_0_, 
flightstat4_.id as id1_6_, 
flightstat4_.code as code2_6_, 
flightstat4_.description as descript3_6_ 
from user_flight userflight0_, 
flight flight1_, 
airport airport2_ 
inner join flight_status flightstat4_ 
on flight1_.flight_status_id=flightstat4_.id 
where userflight0_.flight_id=flight1_.id 
and flight1_.arrival_airport_id=airport2_.id 
and userflight0_.flight_id=? 
and userflight0_.user_id=?

例外

com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: 未知 “on 子句”中的“flight1_.flight_status_id”列

如果我将查询更改为以下内容(只是重新排序 SELECT 值)

查询 2

@Query("SELECT uf.flight.flightStatus, uf.flight.arrivalAirport.iataCode " +
        "FROM UserFlight uf WHERE uf.flight.id=?1 AND uf.user.id=?2")

生成的 SQL

select flight1_.flight_status_id as col_0_0_, 
airport4_.iata_code as col_1_0_, 
flightstat2_.id as id1_6_, 
flightstat2_.code as code2_6_, 
flightstat2_.description as descript3_6_ 
from user_flight userflight0_, 
flight flight1_ 
inner join flight_status flightstat2_ 
on flight1_.flight_status_id=flightstat2_.id, 
airport airport4_ 
where userflight0_.flight_id=flight1_.id 
and flight1_.arrival_airport_id=airport4_.id 
and userflight0_.flight_id=? 
and userflight0_.user_id=? 

它有效,我从数据库中获取结果。

谁能告诉我为什么其中一个工作而另一个不工作?

注意:FlightStatus 是一个实体,而不是字符串值。

【问题讨论】:

  • 呃。去掉那些下划线。看起来很糟糕
  • @FirebladeDan 这就是 Hibernate 生成的 SQL 的样子。
  • @doelleri - 没有我的味道
  • 你使用的是什么版本的休眠?什么版本的 MySQL?
  • Hibernate 版本是 4.3.10.Final

标签: hibernate hql jpql


【解决方案1】:

错误在这里:

在您的第一个查询中:

...
airport airport2_ 
inner join flight_status flightstat4_ 
on flight1_.flight_status_id=flightstat4_.id 
...

所以解释器认为你想链接airport2_flighstat4_,所以ON子句不正确

相反,在第二个查询中,您有:

...
flight flight1_ 
inner join flight_status flightstat2_ 
on flight1_.flight_status_id=flightstat2_.id, 
...

ON 子句关于flight1_flighstat2_ 两个表是正确的

编辑

当你写作时:

SELECT uf.flight.arrivalAirport.iataCode, uf.flight.flightStatus

解释器按以下顺序分解对象:

处理第一个字段:

uf (user_flight) -> flight (flight) -> arrivalAirport (airport)

所以处理第二个字段:

uf (user_flight) -> flight (flight)

这两个对象已经存在于表中,因此它会重用它们,但是 JOIN 的顺序已经定义,所以你有第一个布局(有错误)。

当您更改字段顺序时,(第一个查询的)第二个字段已被第一个处理,旧的第一个作为第二个,因此您有第二个没有错误的布局。

我希望,我的解释很干净 :)

【讨论】:

  • 您能用 HQL 术语而不是生成的 sql 来解释错误吗?我知道错误在哪里,但我不明白为什么更改 HQL SELECT 中的列顺序会导致休眠生成无效的 sql。
  • 谢谢乔,不过有一个问题,这是否意味着我在执行SELECT uf.flight.arrivalAirport.iataCode, uf.flight.flightStatus 时错误地使用了休眠,还是休眠中的错误?
  • 我认为是 Hibernate 的一个错误。但这只是我的意见。
猜你喜欢
  • 2021-05-09
  • 2011-11-05
  • 1970-01-01
  • 1970-01-01
  • 2017-02-21
  • 2015-07-24
  • 2011-01-12
  • 2013-12-06
  • 1970-01-01
相关资源
最近更新 更多