如何在spring app中更好地设置对象字段?

dluptydi  于 2023-04-10  发布在  Spring
关注(0)|答案(1)|浏览(130)

我在下面的Spring应用程序中有实体。

  1. @Entity(name = "products")
  2. public class ProductModel {
  3. @Id
  4. @GeneratedValue(strategy = GenerationType.AUTO)
  5. private UUID id;
  6. private String name;
  7. private String code;
  8. private boolean is_group;
  9. @ManyToOne
  10. private ProductModel group;

和json从前端应用程序

  1. { "id":"50bfddf4-d5f8-11ed-afa1-0242ac120002",
  2. "name":"Phone",
  3. "group_id":"7bd886d0-d5f8-11ed-afa1-0242ac120002"
  4. }

这是我的控制器,我必须通过id productrepo找到

  1. @CrossOrigin
  2. @PostMapping(value = "/product/save",produces = "application/json", consumes="application/json")
  3. void saveProduct(@RequestBody ProductModel productModel){
  4. var group_id=productModel.getGroup_id();
  5. if(group_id!=null && group_id.length()>0){
  6. var group=productRepo.findById(UUID.fromString(group_id)).get();
  7. if(group!=null){
  8. productModel.setGroup(group);
  9. }
  10. }
  11. productRepo.save(productModel);
  12. }

如何将group_id从json转换为ProductModel?
我期待代码的例子

rqdpfwrv

rqdpfwrv1#

在group_id的帮助下,可以从数据库中获取它
示例代码:

  1. @CrossOrigin
  2. @PostMapping(value = "/product/save",produces = "application/json", consumes="application/json")
  3. void saveProduct(@RequestBody ProductModel productModel){
  4. var group_id = productModel.getGroup_id();
  5. if(group_id != null && !group_id.isEmpty()){
  6. UUID groupId = UUID.fromString(group_id);
  7. Optional<ProductModel> optionalGroup = productRepo.findById(groupId);
  8. if(optionalGroup.isPresent()){
  9. ProductModel group = optionalGroup.get();
  10. productModel.setGroup(group);
  11. } else {
  12. // handle error - group not found
  13. }
  14. }
  15. productRepo.save(productModel);
  16. }
展开查看全部

相关问题