Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

Hibernate 映射檔不支援 union:ORA-00907 缺失右括號排查

後台日誌拋出一個看似 SQL 語法錯誤的例外,實際根因卻在 Hibernate 映射檔的 <formula> 裡。

先看例外

org.hibernate.exception.SQLGrammarException: could not execute query
    at org.hibernate.loader.Loader.doList(Loader.java:2214)
    ...
Caused by: java.sql.SQLException: ORA-00907: 缺失右括號

把實際送出的 SQL 抓出來

從 Hibernate 日誌取出被包裹過的查詢,問題集中在 formula 產生的子查詢:

select *
from (
  select this_.SUB_ID as ACID1_1373_0_,
         ......
         (select t.well_name
            from BASE_WELL_INFO t
           where t.well_id =
                 ((select t.well_id from SUPER_TABLE_1 t
                    where t.ID = this_.TASK_ID and rownum = 1 this_.union
                   select t.well_id from SUPER_TABLE_2 t
                    where t.ID = this_.TASK_ID and rownum = 1 this_.union
                   ......
                   and rownum = 1))
            and rownum = 1) as formula1982_0_,
         ......
  from SUB_TABLE this_)
where rownum <= ?

關鍵那一行是 and rownum = 1 this_.union——this_. 被硬塞進 union 中間,括號也沒對稱閉合,Oracle 自然只能回報「缺失右括號」。

映射檔裡的原始寫法

<property name="wellName" type="java.lang.String">
    <formula>
        (select t.well_name
           from base_well_info t
          where t.well_id = ((select t.well_id
           from SUPER_TABLE_1 t
           where t.ID = TASK_ID and rownum = 1
           union
           select t.well_id from SUPER_TABLE_2 t
           where t.ID = TASK_ID and rownum = 1
           union
           ......
           and rownum = 1)
          and rownum = 1)
    </formula>
</property>

根因與解法

Hibernate 在組裝 formula 時,會把未加別名的欄位自動加上 this_. 前綴。當 formula 內含 union 這種集合運算時,這個前綴被塞到 union 的錯誤位置,直接破壞語法。三種可行做法:

一、把 formula 內所有欄位都寫成明確的別名形式,不讓 Hibernate 有機會自動補前綴;二、乾脆不要用 formula,改在 HQL 或原生 SQL 查詢中處理這段邏輯,映射檔只負責純欄位對應;三、把 union 子查詢包成一個完整的内嵌檢視或子查詢並給它別名,讓自動前綴落在合法位置。

實務上第二種最省心。formula 適合簡短的计算式,一旦塞進多表 union 與 rownum,就已經超出它該承擔的複雜度,除錯成本遠高於把邏輯收回查詢層。

Copyright © Linux教程網 All Rights Reserved