在NHibernate中实现复杂的查询?

时间:2010-11-16 16:45:53

标签: sql nhibernate nhibernate-mapping

我一直在使用NHibernate一段时间,但主要是使用基于约定的自动持久性模型生成,然后对对象执行基本的CRUD操作。

我现在需要对遗留系统执行一个相当讨厌的查询以及一个充满参数的手(大多数where子句需要参数化)。我不清楚我是应该定义单个对象然后尝试实现复杂查询还是仅使用本机SQL来定义查询。我也不清楚在hbm.xml文件中定义查询的正确语法。本机SQL查询如下。感谢任何能帮助我解决问题的人。

WITH CTE AS ( SELECT
    substr(KEY1||KEY2||KEY3||'-'||digits(KEY4)||'-'||digits(KEY5),1,17) KEY_ID,
    SUM(CASE WHEN BATCH between 200801001 and 200812999 THEN TRANSACTION_AMOUNT ELSE 0 END) AS _2008AMOUNT,
    SUM(CASE WHEN BATCH between 200901001 and 200912999 THEN TRANSACTION_AMOUNT ELSE 0 END) AS _2009AMOUNT,
    SUM(CASE WHEN BATCH between 201001001 and 201012999 THEN TRANSACTION_AMOUNT ELSE 0 END) AS _2010AMOUNT

    FROM _SCHEMA.TRANSACTIONS

    WHERE OWNER='02'
    AND TRANSACTION_TYPE in ('A','B')
    AND BATCH between 200801000 AND 201012999

    GROUP BY KEY1, KEY2, KEY3, KEY4, KEY5

    HAVING SUM(CASE WHEN BATCH between 200801001 and 200812999 THEN TRANSACTION_AMOUNT ELSE 0 END)  0
    OR SUM(CASE WHEN BATCH between 200901001 and 200912999 THEN TRANSACTION_AMOUNT ELSE 0 END)  0
    OR SUM(CASE WHEN BATCH between 201001001 and 201012999 THEN TRANSACTION_AMOUNT ELSE 0 END)  0
    )


    SELECT
    B.OWNER
    ,CTE1.MAX_ITEM_AMOUNT
    ,CTE1.SUM_ITEM_AMOUNT
    ,B.PRIMARY_SECONDARY_IDENTITY
    ,B.PRIMARY_ID
    ,B.PRIMARY_NAME
    ,B.KEY_ID
    ,B.KEY_AMOUNT
    ,CASE(B.KEYCLASS) WHEN 'C' THEN 'CLASS1' WHEN 'S' THEN 'CLASS2' WHEN 'M' THEN 'CLASS3' WHEN 'F' THEN 'CLASS4' END AS KEYCLASS
    ,NA.PRIMARY_CT AS PRIMARY_CITY
    ,NA.PRIMARY_ST AS PRIMARY_STATE
    ,B.KEY_EFFECTIVE_DATE
    ,B.KEY_ENTRY_DATE
    ,CTE._2008AMOUNT
    ,CTE._2009AMOUNT
    ,CTE._2010AMOUNT
    ,B.EMPLOYEE_NAME

    FROM CTE

    JOIN _SCHEMA.TABLE2 B ON CTE.KEY_ID = B.KEY_ID

    JOIN (
    SELECT
    PRIMARY_SECONDARY_IDENTITY
    , MAX(ITEM_AMOUNT) AS MAX_ITEM_AMOUNT
    , SUM(ITEM_AMOUNT) AS SUM_TTEM_AMOUNT
    FROM CTE
    JOIN _SCHEMA.TABLE2 B ON CTE.KEY_ID = B.KEY_ID
    GROUP BY PRIMARY_SECONDARY_IDENTITY
    ) CTE1 ON CTE1.PRIMARY_SECONDARY_IDENTITY = B.PRIMARY_SECONDARY_IDENTITY

    JOIN _SCHEMA.TABLE3 NA ON B.PRIMARY_ID = NA.KEY1 || DIGITS(NA.KEY2)

    ORDER BY MAX_ITEM_AMOUNT DESC, PRIMARY_SECONDARY_IDENTITY
    

1 个答案:

答案 0 :(得分:5)

此类交易应通过命名查询处理。

NHibernate允许一些预先配置的命名查询,这是简单的CRUD操作无法做到的。我建议你在NHibernate文档中注意这些用法。

15.2. Named SQL queries

另一方面,您可能对本机SQL查询感兴趣。

9.3.5. Queries in native SQL