【发布时间】:2011-07-06 23:15:01
【问题描述】:
我在尝试将 Hibernate 与 MySQL 一起使用时遇到了一个奇怪的错误。我有以下命名查询:
SELECT SUM(s.plotline.value), s.character FROM Story as s WHERE s.chapter.chapterID = ?1 GROUP BY s.character ORDER BY SUM(s.plotline.value)
这将被翻译成以下 SQL 语句:
select sum(plotline1_.Value) as col_0_0_, story0_.CharacterID as col_1_0_, character2_.CharacterID as Characte1_5_,
character2_.AuthorID as AuthorID5_, character2_.BookID as BookID5_, character2_.CharacterName as Characte2_5_,
character2_.LastModified as LastModi3_5_
from fantasy.story story0_, fantasy.plotline plotline1_
inner join fantasy.character character2_ on story0_.CharacterID=character2_.CharacterID
where story0_.PlotlineID=plotline1_.PlotlineID and story0_.ChapterID= 4
group by story0_.CharacterID
order by count(plotline1_.Value)
当我执行这个时,我得到:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'story0_.CharacterID' in 'on clause'
sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
java.lang.reflect.Constructor.newInstance(Unknown Source)
com.mysql.jdbc.Util.handleNewInstance(Util.java:407)
com.mysql.jdbc.Util.getInstance(Util.java:382)
如果我将查询更改为此并直接在 SQL 中运行,它会正常运行:
select sum(plotline1_.Value) as col_0_0_, story0.CharacterID as col_1_0_, character2_.CharacterID as Characte1_5_,
character2_.AuthorID as AuthorID5_, character2_.BookID as BookID5_, character2_.CharacterName as Characte2_5_,
character2_.LastModified as LastModi3_5_
from fantasy.story story0, fantasy.plotline plotline1_
inner join fantasy.character character2_ on CharacterID = character2_.CharacterID
where story0.PlotlineID=plotline1_.PlotlineID and story0.ChapterID= 4
group by story0.CharacterID
order by count(plotline1_.Value)
这个问题分为两部分
- 为什么在连接中删除对 CharacterID 的显式限定会使其工作?我的经验主要是使用 SQL Server,如果您尝试以这种方式编写查询,它实际上会失败。
- 有没有办法让 Hibernate 以正确的形式向我提供查询或调整我的 MySQL 配置,以便它以 Hibernate 生成查询的方式接受查询?
【问题讨论】:
-
我可能已经找到了对第 1 部分的解释 krisgale.com/beware-of-table-alias-in-left-join 似乎 MySQL 决定要求在从版本 5 开始选择的多个表周围加上括号。这无助于我的修复休眠查询,这里的帮助仍然非常感谢