[英]How to .save/POST an array of values from a JSON key value pair in Java spring-boot JPA
I am trying to save an object to my database through a REST .POST and when I am receiving the JSON object from the frontend one of the values from a json key has multiple values in an array form.我正在尝试通过 REST .POST 将对象保存到我的数据库中,当我从前端接收 JSON 对象时,来自 json 键的值之一在数组形式中有多个值。
JSON: JSON:
{ "supportedId": [ 2, 4, 1, 18592, 18594 ], "reportSubscriptionId": 100 }
I want to save each "supportedId" as its own INSERT/Unique entry in the database with "reportSubscriptionId: 100" like the json object above.我想使用“reportSubscriptionId:100”将每个“supportedId”保存为数据库中自己的INSERT/Unique条目,就像上面的json对象一样。
How do I iterate through the array and save this properly?如何遍历数组并正确保存它? Any help would be appreciated, thanks!
任何帮助将不胜感激,谢谢!
@RequestMapping(
method = RequestMethod.POST
)
@ResponseBody
public ApplicationUserSubscription createAppSubscription(@RequestBody ApplicationUserSubscription appUser) {
return applicationUserSubscriptionRepository.save(appUser);
@Repository
public interface ApplicationUserSubscriptionRepository extends
JpaRepository<ApplicationUserSubscription, Integer> {}
Create request class to map input and the create entity by processing input request as below,通过如下处理输入请求来创建请求类来映射输入和创建实体,
Entity:实体:
public class ApplicationUserSubscription {
@Id
private Integer supportedId;
private Integer reportSubscriptionId;
//constructor getter setters
} }
Request:要求:
class ApplicationUserSubscriptionRequest {
private List<Integer> supportedIds;
private Integer reportSubscriptionId;
//contructor getter setters
}
Controller:控制器:
@RequestMapping(method = RequestMethod.POST)
public List<ApplicationUserSubscription> createAppSubscription(@RequestBody ApplicationUserSubscriptionRequest applicationUserSubscriptionRequest) {
List<ApplicationUserSubscription> subscriptions = applicationUserSubscriptionRequest.getSupportedIds().stream()
.map(ele -> new ApplicationUserSubscription(ele, applicationUserSubscriptionRequest.getReportSubscriptionId()))
.collect(Collectors.toList());
return applicationUserSubscriptionRepository.saveAll(subscriptions);
}
Repository:存储库:
@Repository
public interface ApplicationUserSubscriptionRepository extends JpaRepository<ApplicationUserSubscription, Integer> {
}
Hope it helps.希望能帮助到你。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.