java - 使用 Java 和 Hibernate HQL 验证账户余额

标签 java hibernate object accounting

我当前的账户余额对象中有以下属性:

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求和 -从第二次求和中减去第一次求和的结果
- 将减法结果与 userBalance 对象的 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/

相关文章:

java - 如何区分客户端/服务器应用程序中的多个客户端

java - 在camel中,如何通过聚合策略中的aggregate()返回多个交换

java - 如何在方法之外访问已在其他类中实例化的类 A 的成员变量?

mysql - hibernate 不在 mysql 表上生成自动增量约束

c# - 无法将 List<char> 作为参数传递给 List<object>?

javascript - 在不知道属性名称的情况下访问 JavaScript 的对象属性

java - 绘制不同形状java时JColorChooser颜色出现问题

java - 在某些情况下,有没有办法使用 Spring Data JPA Projections 来避免在 @SecondaryTable 上进行联接?

java - 打印作为对象的 TreeMap 值

java - 如何使用 Hibernate 根据产品名称和价格搜索类别?