java - Hibernate 查询 - 复杂

标签 java sql spring hibernate jpa

我目前正在涉足 SQL,并且希望针对我所创建的问题获得一些帮助。

为了练习一些编程,我正在制作一个 IOU 应用程序。下面是我存储的表 我的借条记录(忽略一些相关栏目)。该表允许用户说“嘿,你欠我 X 金额”和“我欠你 X 金额”。

| Creator    |    Type     | User_Involved| Amount |
|:-----------|------------:|:------------:|   
| 1          |    0        |     2        |   3.0
| 2          |    0        |     1        |   4.0
| 3          |    1        |     1        |   5.0

注意:类型表示用户是否“借出或请求资金”。 0 = 四旬期 1 = 已请求

目标:我的目标是获取所有用户及其总欠款金额(负数或正数)的列表。

这变得相当困难,因为我无法进行简单的分组,因为我需要对两列进行分组(Creator 和 User_Involved)。

我设法编写了一个给出正确结果的 SQL 查询,但是我无法将其转换为 Hibernate 版本。

问题主要归结为 JPA 无法执行联合。

有问题的查询:

/** assumption 1 is owed to creator **/

select sum(owed_to_you) as owed_to_you, friend_id
from
(
/** you created **/
select sum(CASE WHEN transaction_type = 0 THEN -amount ELSE amount END) as owed_to_you, friend_involved as friend_id
from iou
where
  creator = 3

group by friend_involved

union all

/** someone else created **/
select sum(CASE WHEN transaction_type = 1 THEN -amount ELSE amount END) as owed_to_you, creator as friend_id
from iou
where
  friend_involved = 3

group by creator) as theunion

group by friend_id

除了将所有 Ious 加载到内存中并以这种方式对其进行排序之外,我完全被难住了。今天我做了很多研究,学到了很多东西,但是,我仍然没有取得进展。

任何帮助将不胜感激。

最佳答案

您可以分别执行两个查询并在 Java 代码中组合结果。

关于java - Hibernate 查询 - 复杂,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41346562/

相关文章:

java - Spring Batch + Spring API REST

java - 为什么这个变量的可访问性与另一个类中一个类的内部类如此不同

java - JavaFX 8 中文本区域的透明背景

java - 从 GridView 更改项目

sql - 在 Postgres 中添加多个列的累积总和

mysql - 如何在特定条件下自连接表

mysql - 是否可以将 SQL 注入(inject)到此查询中?

java - 如何配置 Spring 以尽可能多地节省内存?

java - testng.xml 没有运行来自不同包的多个类

java - 组织.postgresql.util.PSQLException : ERROR: null value in column "category_id" violates not-null constraint