【问题标题】:Spring-boot JPA entity OneToOne adding new child with relation to parentSpring-boot JPA实体OneToOne添加与父级相关的新子级
【发布时间】:2019-03-14 21:28:08
【问题描述】:

我无法弄清楚如何简单地将子实体与现有父实体相关联。

@Entity
@Table(name = "parent")
@Document(indexName = "parent")
public class Parent implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator")
    @SequenceGenerator(name = "sequenceGenerator")
    private Long id;

    @Column(name = "name")
    private String name;

    @OneToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    @JoinColumn(unique = true)
    private Child child;

    //getters, setters
 }

孩子

@Entity
@Table(name = "child")
@Document(indexName = "child")
public class Child implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator")
    @SequenceGenerator(name = "sequenceGenerator")
    private Long id;

    @Column(name = "name")
    private String name;

    @OneToOne(mappedBy = "child")
    private Parent parent;

    //getters, setters
 }

这是两个基本模型。

父级已存在于数据库中,我想添加一个新的子级。

Child childEntity = childRepository.save(child);

子元素填充如下: child.json

{
   "name": "smallChild", 
   "parent": { "id" : "1" } 
}

我希望能够拯救孩子,并让它自动与父母建立关系。

我做了一些非常讨厌的代码......

  1. 为 ID 保存没有父母的孩子
  2. 按 ID 查询数据库的父代
  3. 将子实体设置为父实体
  4. 用新的孩子保存父母
  5. 将父实体设置为子实体
  6. 用父级重新保存子级。

这最终是 6 次数据库查询。

我尝试从 lynda.com 观看一些课程视频,但没有帮助。

谢谢!

【问题讨论】:

    标签: java spring hibernate spring-boot jpa


    【解决方案1】:

    需要父主键或完整实体。 如果父 ID 可用,那么如果目标只是保存,则不需要额外查询来获取父对象。

    如果您有可用的父 ID,那么您可以将子实体保存为:

    Child child = new Child();
    //...
    //Setters for child
    //...
    //Now just create a parent object and set the id to it
    Parent p = new Parent();
    p.SetId(parentId); // as the parentId is already vailable
    child.setParent(p);
    Child childEntity = childRepository.save(child);
    

    【讨论】:

    • 谢谢,我试过了,但我仍然需要运行另一个查询来更新父集线器,否则 parent.childId 为空; JPA 是否有保存或加入某处.. 保存新孩子时也会更新新孩子的父母?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-11
    • 2020-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多