来自多个表的 HQL 计数

发布于 2024-12-10 08:37:33 字数 604 浏览 0 评论 0原文

我想使用 HQL 查询来查询数据库,以检索 MY_DATE 大于 SOME_DATE 的行总数。

到目前为止,我已经想出了一个本机 Oracle 查询来获取该结果,但在用 HQL 编写时我遇到了困难:

SELECT
    (
     SELECT COUNT(MY_DATE) 
     FROM Table1 
     WHERE MY_DATE >= TO_DATE('2011-09-07','yyyy-MM-dd') 
    ) 
    + 
    (
     SELECT COUNT(MY_DATE) 
     FROM Table2 
     WHERE MY_DATE >= TO_DATE('2011-09-07','yyyy-MM-dd')
    ) 
AS total

我实际上有超过 2 个表,但我一直有 IllegalArgumentException (子树意外结束)。

工作的本机 Oracle 基本上以 FROM Dual 结尾。

我应该使用什么 HQL 查询来获取我想要的总行数?

I would like to query my database using a HQL query to retrieve the total number of rows having a MY_DATE greater than SOME_DATE.

So far, I have come up with a native Oracle query to get that result, but I am stuck when writing in HQL:

SELECT
    (
     SELECT COUNT(MY_DATE) 
     FROM Table1 
     WHERE MY_DATE >= TO_DATE('2011-09-07','yyyy-MM-dd') 
    ) 
    + 
    (
     SELECT COUNT(MY_DATE) 
     FROM Table2 
     WHERE MY_DATE >= TO_DATE('2011-09-07','yyyy-MM-dd')
    ) 
AS total

I actually have more than 2 tables but I keep having an IllegalArgumentException (unexpected end of subtree).

The working native Oracle basically ends with FROM dual.

What HQL query should I use to get the total number of rows I want?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

向日葵 2024-12-17 08:37:33

首先,如果您有一个有效的 SQL 查询,为什么不直接使用它而不是尝试将其转换为 HQL?由于您首先返回单个标量,因此您不需要 HQL 提供的任何内容(例如依赖实体等...)

其次,您在 Hibernate 中映射了“双重”吗? :-) 如果没有,您到底打算如何翻译它?

也就是说,“子树意外结束”错误通常是由 Hibernate 的 AST 解析器的特性引起的。常用的解决方法是在表达式前添加“0 +”前缀:

select 0 + (
   ... nested select #1 ... 
       ) + (
   ... nested select #2 ... 
       ) as total
  from <from what exactly?>

First of, if you have a working SQL query, why not just use that instead of trying to translate it to HQL? Since you're returning a single scalar in the first place, it's not like you need anything HQL provides (e.g. dependent entities, etc...)

Secondly, do you have 'dual' mapped in Hibernate? :-) If not, how exactly are you planning on translating that?

That said, "unexpected end of subtree" error is usually caused by idiosyncrasies of Hibernate's AST parser. A commonly used workaround is to prefix the expression with '0 +':

select 0 + (
   ... nested select #1 ... 
       ) + (
   ... nested select #2 ... 
       ) as total
  from <from what exactly?>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文