【问题标题】:HQL does not accept update SQL with joinHQL 不接受带有连接的更新 SQL
【发布时间】:2014-09-26 11:57:40
【问题描述】:

我需要在我的 java 应用程序中将此 SQL 运行到 MySQL 数据库:

update group_table 
join
  (
        select tab1.letter, tab1.id_group_table from 
        (
          select  letter,
          id_group_table, 
          count(letter) as occurrences
          from letter
          group by id_group_table, letter 
          order by occurrences desc
        ) tab1
        group by tab1.id_group_table having max(tab1.occurrences)    

  ) tab2 on group_table.id_group_table = tab2.id_group_table

set champion = tab2.letter
where group_table.id_whatever in (1,2,3,4);

如果我在数据库中尝试它,它会起作用。现在这就是我尝试使用休眠的方法:

String hqlUpdate = "update group_table join (select tab1.letter, tab1.id_group_table from (select  letter,id_group_table, count(letter) as occurrences from letter group by id_group_table, letter order by occurrences desc) tab1 group by tab1.id_group_table having max(tab1.occurrences)) tab2 on group_table.id_group_table = tab2.id_group_table set champion = tab2.letter where group_table.id_whatever in (1,2,3,4);";
getSession().createQuery( hqlUpdate ).executeUpdate();

这是我得到的错误:

Ago 04, 2014 12:16:18 AM org.hibernate.hql.internal.ast.ErrorCounter reportError
ERROR: line 1:38: expecting "set", found 'JOIN'
line 1:38: expecting "set", found 'JOIN'
    at antlr.Parser.match(Parser.java:211)
    at org.hibernate.hql.internal.antlr.HqlBaseParser.setClause(HqlBaseParser.java:414)

我需要运行这个确切的查询... 我如何使用休眠来做到这一点

谢谢!!

【问题讨论】:

  • 使用原生 SQLQuery,而不是 HQL 和 Session.createSQLQuery()

标签: java mysql sql hibernate hql


【解决方案1】:

试试下面的代码

String hqlUpdate = "update group_table join (select tab1.letter, tab1.id_group_table from (select  letter,id_group_table, count(letter) as occurrences from letter group by id_group_table, letter order by occurrences desc) tab1 group by tab1.id_group_table having max(tab1.occurrences)) tab2 on group_table.id_group_table = tab2.id_group_table set champion = tab2.letter where group_table.id_whatever in (1,2,3,4);";     
getSession().createSQLQuery( hqlUpdate ).executeUpdate();

【讨论】:

    【解决方案2】:

    如果您需要精确查询,则不要使用 HQL,而是使用 native query support

    【讨论】:

      猜你喜欢
      • 2011-09-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-09
      • 2019-01-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多