【问题标题】:Spring data jpa @OneToMany bidirectional on same tableSpring data jpa @OneToMany 在同一张表上双向
【发布时间】:2021-11-15 15:15:02
【问题描述】:

我正在尝试为单个表关系(如 orgChart)创建一个简单的映射。 我正在将 Spring Boot 与 Spring 数据和 JPA 一起使用。 这是我的实体:

@Entity
@Table(name = "orgchart")
public class OrgChart {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;

    @ManyToOne
    private OrgChart parent;

    @OneToMany
    @JoinColumn(name = "parent_id")
    private List<OrgChart> children = new ArrayList<>();
}

以及添加一些数据的测试代码:

OrgChart orgChart = new OrgChart();

OrgChart orgChart1 = new OrgChart();
orgChartRepository.save(orgChart1);

OrgChart orgChart2 = new OrgChart();
orgChartRepository.save(orgChart2);

orgChart.getChildren().add(orgChart1);
orgChart.getChildren().add(orgChart2);
OrgChart saved = orgChartRepository.save(orgChart);

所以表格创建正确,结构对我来说也不错:

id |parent_id|
---+---------+
361|         |
359|      361|
360|      361|

但问题是当我从数据库中获取对象时,我看不到对象中的父字段:

List<OrgChart> children = orgChartRepository.getById(saved.getId()).getChildren()

这里children.get(0).getParent() 始终为空。我究竟做错了什么?我已经尝试了很多方法,这件事有可能实现吗? 谢谢。

【问题讨论】:

    标签: spring jpa spring-data-jpa spring-data


    【解决方案1】:

    尝试@OneToMany(mappedBy="parent") 告诉 JPA 这些字段是双向关系的两端,而不是两个不同的单向。

    【讨论】:

    • 它不起作用
    • 这可能是因为保存双向关系时,必须设置拥有端。在这种情况下,拥有方是parent 字段,因此请在保存orgChart1 之前尝试orgChart1.setParent(orgChart)
    • 如果我设置了父级,那么当我获取数据时,我只会看到父级而不再看到子级。如果我同时设置两者,我会收到 stackoverflow 错误。
    【解决方案2】:

    以下应该完成它:

        @OneToMany(cascade = CascadeType.ALL, mappedBy="parent", orphanRemoval = true)
        private List<OrgChart> children = new ArrayList<>();
        
        @ManyToOne
        @JoinColumn(name = "parent_id")
        private OrgChart parent;
        
        OrgChart parent = new OrgChart();
        OrgChart newOrgChart = new OrgChart();
        newOrgChart.setParent(parent);
        parent.getChildren().add(newOrgChart);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-17
      • 1970-01-01
      • 2016-01-09
      • 1970-01-01
      • 2021-09-15
      • 2021-07-14
      相关资源
      最近更新 更多