2016-04-25 84 views
0

我需要使用Hibernate做一個hql/sql查詢,但我不知道我在Hibernate中究竟該如何實現。後端數據庫是SQL Server。休眠 - 簡單的數據,但複雜的sql查詢

我有與主狀態交易表 - 掛起,存款,清除&反彈。

交易 - 表1

Seq Receipt ID  Status 
1  1234   Pending 
2  2345   Deposited 
3  3456   Cleared 
4  4567   Bounced 

最初記錄在Pending。記錄的移動是from Pending to Deposit,然後是from Deposit to either Cleared or Bounced。根據狀態更改爲ClearedBounced它在另一個表中插入數據 - Table 2這是工作的罰款只是

當前HQL查詢從Table 1讀取數據,並尋找在Table 2相同的狀態特定收據ID。像下面

Select receiptID from Table1 where table1.status in ('Bounced','Cleared') 
and not exists (select table2.receiptID from Table2 where 
table1.receiptID = table2.receiptID and table2.status in ('Cleared','Bounced')) 

這工作不錯,到目前爲止,作爲在任一時間點的東西會出現在表2任Cleared or Bounced的1條。

新變化

現在所需要的變化是Table2進入記錄Deposit爲好。所以,當狀態從Pending to Deposit變化時,我需要在Table2中輸入數據。

現在很明顯,僅僅通過添加狀態爲Deposit在上面的查詢將不起作用。由於它對Deposit工作正常,但是當狀態將從Deposit to Cleared/Bounced更改時,系統將在Table2(子查詢)中找到Deposit中的現有記錄,因此它不會爲Cleared or Bounced輸入任何新記錄。 :(

我想我可以與工會做到這一點,但不知道我怎麼實現它在休眠(HQL),沒有任何複雜的查詢。

幫助PLZ !!!

回答

0

經過大量的思考,是我能夠找到一個解決辦法。我只需要添加一個不存在對特定的表1和存款表2清晰的狀態。

新的查詢看起來像

Select receiptID from Table1 where table1.status in ('Deposit','Bounced','Cleared') 
     and not exists (select table2.receiptID from Table2 
          where table1.receiptID = table2.receiptID 
          and table2.status in ('Cleared','Bounced') 
          and table1.status = table2.status) 
     and not exists (select table2.receiptID from Table2 
          where table1.receiptID = table2.receiptID 
          and table1.status in ('Deposit' 
          and table2.status in ('Cleared'))