【问题标题】:Simple difficulty with HQL QueryHQL 查询的简单困难
【发布时间】:2012-12-22 10:53:12
【问题描述】:

我在执行这样的 HQL 查询时遇到问题:

select new myPackage.view.CoverDocumentReportView(Re.code AS fulCd,
Re.creditPrice AS crtprc,
Re.debitPrice  AS dbtprc,
(Re.debitPrice - Re.debitPrice) AS redbtprc,
(Re.creditPrice- Re.creditPrice) AS recrtprc,
(Re.debitPrice-Re.creditPrice)   AS rem) 
from 
(select  fullCode as code, 
     sum(creditPrice) as creditPrice ,
     sum(debitPrice)  as debitPrice   
from    DocumentMaster DM,
     DocumentAccount   DA,
     Tree              T ,
     AccountTree       AT, 
     DocumentDetailed  DD 
where DM.id =  DA.documentMaster  and  
      DA.accountTree =  T.id      and   
      DA.accountTree =  AT.id     and   
      DD.documentAccount =  DA.id 
group by  DA.accountTree ) As Re


1) 如果我像这样执行:
SQLQuery crit = (SQLQuery) session
            .createSQLQuery(sql).setResultTransformer(Transformers.aliasToBean(CoverDocumentReportView.class));
ArrayList<CoverDocumentReportView> li =  (ArrayList<CoverDocumentReportView>) crit.list();

ERROR 2012-12-22 14:16:19,838 [http-8080-1] org.hibernate.util.JDBCExceptionReporter:您的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册,了解在 '.datx.web.accounting.view.CoverDocumentReportView(Re.code AS fulCd, 第 1 行的 Re.creditP'


2) 如果我用这个执行它:
Query query = session.createQuery(sql).setResultTransformer(Transformers.aliasToBean(CoverDocumentReportView.class));
ArrayList<CoverDocumentReportView> li =  (ArrayList<CoverDocumentReportView>)query.list();

错误将是:

错误 2012-12-22 14:51:46,709 [http-8080-1] org.hibernate.hql.ast.ErrorCounter:第 1:224 行:意外令牌:( 错误 2012-12-22 14:51:46,709 [http-8080-1] org.hibernate.hql.ast.ErrorCounter:第 1:308 行:意外令牌:总和

有什么问题?

【问题讨论】:

标签: mysql hibernate hql


【解决方案1】:

SQL 和 HQL 是两种不同的语言。

HQL 不支持 from 子句中的子查询,因此该查询不能是 HQL 查询。

并且 SQL 不知道 Java 对象,并且没有任何 new() 函数允许创建它们,因此该查询也不是有效的 SQL 查询。

使其成为有效的 SQL 查询,使用 createSQLQuery() 执行它,然后遍历结果并从返回的行创建对象的实例。或者像你正在做的那样使用结果转换器,它会为你做到这一点。结果转换器将使用您分配给 SQL 查询的返回列的别名来为您创建 bean。您不需要在查询中使用任何 new CoverDocumentReportView() 即可使其正常工作。有关详细信息,请阅读 javadoc。

【讨论】:

  • 感谢您的帮助。但是,在这里将其更改为 SQL 不是一种选择。如何使它与 HQL 一起使用?似乎 HQL 确实支持子查询。我会做任何必要的改变。
  • docs.jboss.org/hibernate/core/3.6/reference/en-US/html_single/… : 请注意,HQL 子查询只能出现在 select 或 where 子句中。
  • 我明白了,但是有没有办法将我想要的 SQL 语句安全地转换为 HQL?一个链接或提示就足够了。
  • 请注意,HQL 子查询只能出现在 select 或 where 子句中。。这意味着您不能from 子句中有子查询。所以,不,这个查询不能被翻译成 HQL,因为 from 子句不是 select 子句,也不是 where 子句。我不明白它怎么能更清楚。
  • 相信我:我明白了 :-) 你不需要每次都重复。我想我最好自己想想how to write this sql without from clause to make it transformable to hql
猜你喜欢
  • 2013-08-19
  • 1970-01-01
  • 1970-01-01
  • 2011-07-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多