SpringData级联保存对象

映射关系如下

 @OneToMany(mappedBy = "kongCluster", cascade = CascadeType.PERSIST)
    private Set clusterMachineSet = new LinkedHashSet();
@ManyToOne
    @JoinColumn(name = "cluster_id", nullable = false)
    private KongCluster kongCluster;

关联的子对象要手动设置父对象,否则保存时会出现外键值为空的问题

@PostMapping(value = {"add"})
    public AjaxResult add(@RequestBody KongCluster kongCluster) {

        try {
            if (kongCluster.getClusterMachineSet() != null
                && !kongCluster.getClusterMachineSet().isEmpty()) {
                kongCluster.getClusterMachineSet().forEach(machine -> {
                    machine.setKongCluster(kongCluster);
                });
            }
            kongClusterRepository.save(kongCluster);
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(e.getMessage());
        }
        return new AjaxResult();
    }

 

你可能感兴趣的:(JPA)