【问题标题】:Transforming a query response in Java Spring Boot在 Java Spring Boot 中转换查询响应
【发布时间】:2021-11-01 00:20:42
【问题描述】:

我有一个表存储在 postgres 数据库中,如下所示

offerId  warehouseId  type   quantity
  1          1         A       2
  1          1         B       5
  

调用数据库获取上述数据后,需要将其转换为类型的响应

{
   offerId : 1,
   warehouseId : 1,
   types : [{type :'A' ,quantity:2} , {type : 'B' , quantity:5}]
}

有没有办法使用 java spring boot 来做到这一点?或任何执行相同操作的 SQL 查询?

【问题讨论】:

  • 你有没有尝试过什么?
  • 我试过了,没有运气,但是我对后端很陌生,所以我很挣扎
  • 结帐 jOOQ Multiset blog.jooq.org/…
  • 请澄清您的具体问题或提供更多详细信息以准确突出您的需求。正如目前所写的那样,很难准确地说出你在问什么。

标签: java postgresql spring-boot spring-data-jpa spring-webflux


【解决方案1】:

对于 SQL Server,您可以在 SQL 语句的末尾添加 FOR JSON AUTO,这将生成 SQL 结果的 JSON 字符串,因此:

SELECT offerId, warehouseId, type, quantity FROM your_table FOR JSON AUTO;

在 MySQL 中您可以使用 JSON_OBJECT:

SELECT JSON_OBJECT ('offerId', offerId, 'warehouseId', warehouseId, 'type', type, 'quantity', quantity) FROM your_table;

编辑: 按如下方式创建 Types JSON 对象数组:

在 Java 中:

//Creating a json array
JSONArray Types = new JSONArray();

//Creating a JSONObject object
JSONObject type = new JSONObject();
type.put("type", "A");
type.put("quantity", 1);

Types.add(type);

JSONObject type1 = new JSONObject();
type1.put("type", "B");
type1.put("quantity", 2);

Types.add(type1)

在 Javascript 中:

function type(type_, quantity) {
  this.type_ = type_;
  this.quantity = quantity;
 }

// create array Types
var Types = [];
// add objects to the array
Types.push(new type("A", 1));
Types.push(new type("B", 2));

【讨论】:

  • 我需要问题中提到的类型的响应类型属性将是一个对象数组,每个对象都有一个类型属性和一个数量属性对应于offerId和nodeId,我相信这不会解决问题,感谢您的回答。可以使用 java 完成吗?
  • 好的,密码。我已经扩展了我对 types 属性的回答!
猜你喜欢
  • 1970-01-01
  • 2023-02-15
  • 1970-01-01
  • 2022-12-20
  • 2019-05-17
  • 1970-01-01
  • 2020-02-05
  • 2018-06-02
  • 2018-11-30
相关资源
最近更新 更多