[英]Spring Boot: Get required columns from API based on user request
I am trying to implement an API endpoint where a user can request required columns from the API我正在尝试实现一个 API 端点,用户可以在其中从 API 请求所需的列
Basically, this is what I want: This is my products table entity基本上,这就是我想要的:这是我的产品表实体
@Entity
@Table(name ="products")
class product{
private Long id;
private String itemName;
private String itemDesc;
private double quantity;
private double purchaseRate;
private double saleRate;
private double onlineSaleRate;
.
.
.
constructor()
getter & setter
}
***And my endpoint is: localhost:8080/api/v1/products
***我的端点是:
localhost:8080/api/v1/products
Requirement: I want to write an api endpoint where i request columns based on requirementsa and get those as response要求:我想编写一个 api 端点,我在其中根据要求请求列并将这些列作为响应
Example: If i only need - itemName, itemPrice and quantity i'll return those as response only.示例:如果我只需要 - itemName、itemPrice 和数量,我将仅将它们作为响应返回。 if some user has requirement of itemName, purchaseRate, saleRate, quantity he will get those as a response only.
如果某些用户对 itemName、purchaseRate、saleRate、数量有要求,他只会得到这些作为响应。
Right now i am writing new endpoints as per requirements, but i think there is some way to do this.现在我正在根据要求编写新的端点,但我认为有一些方法可以做到这一点。
I want to implement this in my application, i tried google for this but there is no search query that is resulting me as per my requirement.我想在我的应用程序中实现这一点,我为此尝试了谷歌,但没有根据我的要求产生的搜索查询。
Create a class with all the fields of your entity with the field types of nullable boxed Boolean (for the purpose of the request json).创建一个 class ,其中包含实体的所有字段,字段类型为可空的盒装 Boolean(用于请求 json)。
class ProductColumns {
private Boolean itemName;
private Boolean itemDesc;
...
// setters and getters
}
Then, to construct a custom response, you can use a java Map to acheive this:然后,要构建自定义响应,您可以使用 java Map 来实现:
public ResponseEntity<Object> getFilteredColumns(ProductColumns columns) {
Map<String, Object> map = new HashMap<String, Object>();
if (columns.getItemName() == true) {
map.put("itemName", [your repo/service method for getting the particular value]);
}
if (columns.getItemDesc() == true) {
map.put("itemDesc", your repo/service method for getting the particular value]);
}
...
return ResponseEntity<Object>(map, HttpStatus.OK);
}
Of course you should wrap it in some try-catch
to your liking.当然,您应该根据自己的喜好将其包装在一些
try-catch
中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.