我当前的账户余额对象中有以下属性:
long id; // Database ID
Date date; // date when this balance object was created
boolean currentBalanceFlag; // indicates this is the most recent balance
float amount; // the total sum currently in the account balance
float depositAmount; // amount deposited that resulted in this objects amount
float withdrawalAmount; // amount withdrawn that resulted in this objects amount
Balance lastBalance; // last balance object for traversing
User user; // owner of the balance
String note; // detailed description of transaction that resulted in current blanace
天平上只执行了两个操作。存款和取款。
问题是:
如何创建 HQL 查询以:
-对用户
的所有depositAmount
求和
-对用户
的所有withdrawalAmount
求和
-从第二次求和中减去第一次求和的结果
- 将减法结果与 user
中 Balance
对象的 amount
进行比较,该对象的 currentBalanceFlag
等于 true
伪代码:
resultAmount = select ( sum(depositAmount) - sum(withdrawalAmount) ) from Balance where user=user
amount = select amount from Balance where user=user and currentBalanceFlag=true
我希望使用 HQL 查询从单次调用数据库中获得最终的 boolean 结果:
resultAmount == amount
最佳答案
select (sum(flow.depositAmount) - sum(flow.withdrawalAmount) - current.amount)
from Balance flow, Balance current
where flow.user=:user
and current.user=:user
and current.currentBalanceFlag=true
这将返回所有流量总和与当前余额之间的差值。
附带说明一下,您不必检查数据的完整性。除非您有无数行,否则使用 SQL 总和计算当前余额应该足够快。
关于java - 使用 Java 和 Hibernate HQL 验证账户余额,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4807294/