【问题标题】:Not able to save parent id when handling OneToMany relationship处理 OneToMany 关系时无法保存父 ID
【发布时间】:2019-03-31 01:40:46
【问题描述】:

我在通过 Spring JPA 维护一对多关系时遇到了一些困难。我们有两个实体父母和孩子。我已经定义了这样的多对一关系

父实体

@OneToMany(cascade = CascadeType.ALL, mappedBy = parent)
Set<Child> childs;

子实体

@ManyToOne
@JoinColumn(name=""parent_id)
private Parent parent;

以下是我的服务中用于保存父级的代码。

Parent parent = new Parent();
parent.setName("name");
List<Child> children= new ArrayList<>();
Child child1 = new Child();
child1.setAge(10);
children.add(child1);
Child child2 = new Child();
child2.setAge(11);
children.add(child1);
parent.setChilds(children)
parentReposiroty.save(parent);

它在两个表中保存数据,但在子表中 parent_id 为空。请提出我在这里缺少的内容。

【问题讨论】:

    标签: spring-boot spring-data-jpa


    【解决方案1】:

    在管理双向关系时,您还应该在从父方保存时为每个子项设置父项。因此,请参阅下面的代码以通过添加 child1.setParent(parent);child2.setParent(parent); 来更新您的代码以设置孩子的父母

    Parent parent = new Parent();
    parent.setName("name");
    List<Child> children= new ArrayList<>();
    Child child1 = new Child();
    child1.setAge(10);
    
    child1.setParent(parent);
    
    children.add(child1);
    Child child2 = new Child();
    child2.setAge(11);
    
    child2.setParent(parent);
    
    children.add(child1);
    parent.setChilds(children)
    parentReposiroty.save(parent);
    

    【讨论】:

      猜你喜欢
      • 2020-11-03
      • 2019-07-08
      • 2018-11-06
      • 1970-01-01
      • 1970-01-01
      • 2020-12-03
      • 2019-01-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多