【问题标题】:Hibernate - Simple data but complex sql queryHibernate - 简单数据但复杂的 sql 查询
【发布时间】:2016-08-18 23:15:27
【问题描述】:

我需要使用 Hibernate 进行 hql/sql 查询,但我不知道如何在 Hibernate 中实现这一点。后端数据库是 SQL Server。

我有主状态的事务表 - 待处理、存款、清除和退回。

交易 - 表 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 中都会有 1 条 Cleared or Bounced 记录。

新变化

现在所需的更改是在Table2 中输入Deposit 的记录。因此,当状态从Pending to Deposit 发生变化时,我需要在Table2 中输入数据。

现在显然,仅仅通过在上面的查询中添加状态为Deposit 是行不通的。因为它对于Deposit 可以正常工作,但是当状态从Deposit to Cleared/Bounced 更改时,系统将在Table2(子查询)中找到Deposit 的现有记录,因此它不会为@ 输入任何新记录987654341@。 :(

我认为我可以通过联合来做到这一点,但不确定如何在 Hibernate (HQL) 中实现它而无需任何复杂的查询。

请帮忙!!!

【问题讨论】:

    标签: sql sql-server hibernate hql


    【解决方案1】:

    经过深思熟虑,是的,我能够找到解决方案。我只需要为 Table1 的存款和 Table2 的清除添加另一个不存在的条件。

    新查询看起来像

    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') )
    

    【讨论】:

      猜你喜欢
      • 2011-07-02
      • 2021-11-12
      • 1970-01-01
      • 1970-01-01
      • 2012-09-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-15
      相关资源
      最近更新 更多