Hibernate MySQL查询错误加入时的未知列

时间:2011-03-02 02:07:41

标签: java mysql sql hibernate

我在尝试将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)

这个问题分为两部分

  1. 为什么在联接中删除CharacterID的显式限定条件会使其工作?我的经验主要是使用SQL Server,如果您尝试以这种方式编写查询,它实际上会失败。
  2. 有没有办法让Hibernate以正确的形式给我查询或调整我的MySQL配置,以便它以Hibernate生成它的方式接受查询?

1 个答案:

答案 0 :(得分:0)

  1. “character”是MySQL中的保留字。这可能是抛弃查询的原因吗?

  2. 您可以强制Hibernate通过在映射文档中的反引号中包含表或列名称来在生成的SQL中引用标识符。 Hibernate将为SQL Dialect使用正确的引用样式(通常是双引号,但SQL Server的括号和MySQL的反引号)。