【问题标题】:How do you save entities with a bidirectional relationship from the non-owning side?如何从非拥有方保存具有双向关系的实体?
【发布时间】:2020-09-16 13:02:00
【问题描述】:

nodes 是使用 Spring Data/JPA 的拥有方的情况下,用双向关系表示下表的最佳方式是什么?我希望能够用node_node 保存nodes 并保存node_node

节点

  • 身份证

node_node

  • node_id_1

  • node_id_2

这是我目前所拥有的。与NodeNode 作为拥有方的双向关系意味着当我在parentschildrenNode 中创建、更新或删除元素时,它不会被持久化。当我通过添加到parentchildren 来更新Node 时,它似乎可以工作,但是当我通过删除来更新时,它就不起作用了。我需要通过NodeNode 保存,因为它是拥有方,但这太麻烦了,因为它需要保存到NodeNodeNode

public class Node {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private Long id;

    @OneToMany(mappedBy = "parent", fetch = FetchType.EAGER, cascade = CascadeType.ALL, orphanRemoval = true)
    private Set<NodeNode> parents;

    @OneToMany(mappedBy = "child", fetch = FetchType.EAGER, cascade = CascadeType.ALL, orphanRemoval = true)
    private Set<NodeNode> children;

}

public class NodeNode {

    @ManyToOne
    @JoinColumn(name = "node_id_1")
    private Node parent;

    @ManyToOne
    @JoinColumn(name = "node_id_2")
    private Node child;

}

目标是能够保存 Node 以及对 Node.parentsNode.children 的任何更改,并同时保存 NodeNode

【问题讨论】:

  • “最好”是什么意思?没有说明它是基于意见的。
  • @JensSchauder 我想了解实现它的标准方式。我要求它工作的方式是我想要实现它的方式,但它可能不是最佳解决方案。

标签: jpa mapping


【解决方案1】:

最佳解决方案是将OneToManyManyToOne 替换为ManyToMany 关系,并使用Node 而不是引用NodeNode

@ManyToMany(fetch = FetchType.EAGER, cascade = { CascadeType.MERGE, CascadeType.REFRESH,  CascadeType.DETACH })
@JoinTable(name = "node_node", joinColumns = @JoinColumn(name = "node_id_1"), inverseJoinColumns = @JoinColumn(name = "node_id_2"))
private Set<Node> children;

@ManyToMany(fetch = FetchType.EAGER, mappedBy = "children")
private Set<Node> parents;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-07-12
    • 2012-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-18
    • 1970-01-01
    相关资源
    最近更新 更多