使用WITH Clause在Hibernate本机查询中没有得到结果

时间:2018-02-19 13:59:58

标签: sql hibernate db2 native-sql

我有一个以" WITH"开头的以下查询条款。如果我在具有DB2连接的SQuirrel中触发相同的查询 - 它可以工作。但是同样的查询在Hibernate Native SQL中返回空数组。

 WITH edd_translated_article_tmp (article_id, tran_article_id, tran_article_title, 
 article_url, source, tran_content ) 
 AS (SELECT M.original_article_id  AS article_id, 
            M.article_id           AS TRAN_ARTICLE_ID, 
            M.article_title        AS TRAN_ARTICLE_TITLE, 
            M.article_url, 
            M.primary_source       AS SOURCE, 
            M.article_content_html AS TRAN_CONTENT 
     FROM   db2admin.edd_searched_article_main M 
     WHERE  M.original_article_id = 5239415) 
SELECT A.article_id, 
   A.article_title, 
   A.article_url, 
   A.primary_source       AS SOURCE, 
   A.article_content_html AS CONTENT, 
   M.tran_article_id      AS TRAN_ARTICLE_ID, 
   M.tran_article_title   AS TRAN_ARTICLE_TITLE, 
   M.tran_content         AS TRAN_CONTENT
FROM   db2admin.edd_searched_article_main AS A 
   LEFT OUTER JOIN edd_translated_article_tmp M 
                ON A.article_id = m.article_id
WHERE  A.article_id = 5239415 

Hibernate Native Query Code:

Query query = getSession().createSQLQuery(sqlNativeQuery);
query.list()

1 个答案:

答案 0 :(得分:1)

假设您使用正确的DB2方言和Hibernate,您的查询应该尽我所知。例如,如果您使用的是一种不支持CTE的非常古老的方言,那么它可能无效。

要获得解决方法,您始终可以将CTE内联到原始查询中:

SELECT
    a.article_id, 
    a.article_title, 
    a.article_url, 
    a.primary_source       AS SOURCE, 
    a.article_content_html AS CONTENT, 
    m.tran_article_id      AS TRAN_ARTICLE_ID, 
    m.tran_article_title   AS TRAN_ARTICLE_TITLE, 
    m.tran_content         AS TRAN_CONTENT
FROM db2admin.edd_searched_article_main AS a
LEFT OUTER JOIN
(
    SELECT
        original_article_id  AS article_id,
        article_id           AS TRAN_ARTICLE_ID, 
        article_title        AS TRAN_ARTICLE_TITLE, 
        article_url, 
        primary_source       AS SOURCE, 
        article_content_html AS TRAN_CONTENT 
    FROM db2admin.edd_searched_article_main
    WHERE original_article_id = 5239415
) m
    ON a.article_id = m.article_id
WHERE
    a.article_id = 5239415 ;