JPA map relation entity parentID
Asked Answered
W

1

0

could someone help me to understand how can I define an entity with JPA mapping that has a relation with it self?

For example, my entity is CompanyDivision, divisionA contains divisionB, divisionC and divisionB contains divisionB1, divisionB2

  • divisionA
    • divisionB
      • divisionB1
      • divisionB2
    • divisionC

Thank you!

Warrigal answered 30/4, 2010 at 10:42 Comment(0)
S
6

It's not different from a relation between 2 different Entities. Here's an example:

class CompanyDivision {

    @OneToMany(mappedBy = "parentDivision")
    private Set<CompanyDivision> childDivisions = new HashSet<CompanyDivision>();

    @ManyToOne
    @JoinColumn(name = "FK_PARENT_DIVISION")
    private CompanyDivision parentDivision;
}
Sverre answered 30/4, 2010 at 10:53 Comment(1)
Do note the remarks in the answer here: https://mcmap.net/q/1334486/-how-would-i-map-a-parent-child-relation-on-same-object-with-jpa when storing things this way.Temptation

© 2022 - 2024 — McMap. All rights reserved.