Spring Rest Hibernate创建嵌套对象

时间:2019-05-11 16:28:08

标签: java spring hibernate spring-mvc spring-rest

我有3个模型PaymentPlan,PaymentPlanDetail,PaymentPlanElement

PaymentPlan具有一个或多个PaymentPlanDetail, PaymentPlanElement具有一个或多个PaymentPlanDetail,

存在以下关系:

public class PaymentPlan{

  //

  @OneToMany(mappedBy = "paymentPlan",cascade = CascadeType.ALL)
  private List<PaymentPlanDetail> paymentPlanDetails= new ArrayList<>();  
}

public class PaymentPlanDetail{

  //

  @ManyToOne(name = paymentPlanElementId)
  private PaymentPlanElement paymentPlanElement;  
}

public class PaymentPlanElement{

  //

  @OneToMany(mappedBy = "paymentPlanElement",cascade = CascadeType.ALL)
  private List<PaymentPlanDetail> paymentPlanDetails= new ArrayList<>  
}

我发送的请求对象看起来像

 {
    name:'foo',

    paymentPlanDetails: [
      {
        name: 'bar',
        paymentPlanElement:{
          id: 12,
          style: 'baz'
        }
      }
    ]

  }

付款计划元素已经创建, 我想发送JSON对象并保存包括付款计划详细信息在内的付款计划,但是出现了payment_plan_id is null错误, 有什么办法可以在一次交易中做到这一点吗?

编辑: 我的PaymentPlan控制器

@RestController
@RequestMapping("/api/payment-plans")
@CrossOrigin(origins = "http://localhost:4200")
@RequiredArgsConstructor
public class PaymentPlanController {

  private final PaymentPlanService paymentPlanService;

  @PostMapping
  public PaymentPlan create(@RequestBody PaymentPlan paymentPlan) {
    return paymentPlanService.create(paymentPlan);
  }

}

和PaymentPland DTO

public interface PaymentPlanDao extends JpaRepository<PaymentPlan, Integer> { }

1 个答案:

答案 0 :(得分:0)

cv

希望有帮助。