Home > Mobile >  Spring data jpa @OneToMany bidirectional on same table
Spring data jpa @OneToMany bidirectional on same table

Time:09-23

I'm trying to create a simple mapping for a single table relation like an orgChart. I'm using Spring Boot with Spring data and JPA. This is my Entity:

@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<>();
}

and the test code to add some data:

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);

so the table is created properly and the structure looks also ok to me:

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

but the problem is that I don't see the parent field in the object when I fetch it from the DB:

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

here children.get(0).getParent() is always null. What am I doing wrong? I've already tried so many ways, is this thing possible to achieve? Thanks.

CodePudding user response:

Try @OneToMany(mappedBy="parent") to tell JPA that these fields are the two ends of a bidirectional relationship, not two different unidirectional ones.

CodePudding user response:

The following should accomplish it:

    @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);
  • Related