我有一个存储货币的枚举:
public enum Currency {
USD,EUR,GBP
}
我的销售实体包含货币作为财产:
public class Sales {
private Long id;
private Merchant merchant;
private Customer customer;
private double amount;
private Currency currency;
}
销售样本表数据如下:
+----+-------------+-------------+--------+----------+
| id | merchant_id | customer_id | amount | currency |
+----+-------------+-------------+--------+----------+
| 1 | 2 | 3 | 125.0 | EUR |
| 2 | 1 | 2 | 135.0 | USD |
| 3 | 3 | 5 | 140.0 | GBP |
| 4 | 2 | 8 | 25.0 | USD |
| 5 | 4 | 8 | 95.0 | EUR |
| 6 | 6 | 9 | 85.0 | EUR |
| 7 | 5 | 6 | 90.0 | USD |
| 8 | 1 | 1 | 225.0 | EUR |
| 9 | 7 | 2 | 350.0 | GBP |
| . | . | . | . | . |
| . | . | . | . | . |
| . | . | . | . | . |
| . | . | . | . | . |
+----+-------------+-------------+--------+----------+
这是我的自定义数据模型
public class CustomDataModel{
private Integer count; //record count
private double total; // its total amount for specified currency
private Currency currency; // it also could be String, it is doesn't matter
}
我的查询参数: merchant_id 和 customer_id 。
我希望将结果设为 List<CustomDataModel>
,例如:
[
{
"count":5,
"total":674.00,
"currency":"USD"
},
{
"count":3,
"total":561.00,
"currency":"EUR"
},
{
"count":4,
"total":715.00,
"currency":"GBP"
}
]
是否可以获得这样的结果。如果是我该怎么办?
答案 0 :(得分:0)
我想你希望按货币获得List<CustomDataModel>
组。如果是这样,则无需依赖merchant_id
或customer_id
。
您可以在存储库中添加以下@Query
方法,如下所示:
@Query("select new com.demo.spring.domain.CustomDataModel(count(s), sum(s.amount), s.currency) from Sales s group by s.currency")
List<CustomDataModel> getGroupByCurrency();
只需确保将整数转换为Long,然后在private Integer count;
类中将private Long count;
转换为CustomDataModel
,并将以下构造函数添加到其中:
public CustomDataModel(Long count, double total, Currency currency) {
super();
this.count = count;
this.total = total;
this.currency = currency;
}
如果您想按商家和客户分组,可以将上述分组更新为...group by s.currency, s.merchant, s.customer