Issue
I have a two classes, parent and child, and at child side I have a relation to itself. The database is modeled on two separate tables, both parent and child share the same "id", and the column "holder" is as foreign key for itself. I wrote the following code. I'm learning and I soon fall into this complex example of inheritance and interrelation and I would like to know if I used the notations correctly.
Person.class
@Entity @Getter @Setter @NoArgsConstructor @Inheritance(strategy = InheritanceType.JOINED) @Table(name = "person") public class Person { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id") private Integer id; @NotNull @Column(name = "name") private String name; }
Member.class
@Entity @Getter @Setter @NoArgsConstructor @Table(name = "member") public class Member extends Person { @NotNull @Column(name = "member_type") private Integer memberType; @Column(name = "id_holder") private Integer idHolder; @ManyToOne(targetEntity = Member.class) @JoinColumn(name = "id_holder", referencedColumnName = "id", insertable = false, updatable = false) private Member holder; @OneToMany(mappedBy = "holder", cascade = CascadeType.ALL) private List<Member> dependents; }
And my object that will populate these entities on frontend is:
Member.model
export class Member { constructor( public id?: number, public name?: string, public memberType?: number, public idHolder?: any ) {} }
Solution
Answering my own question:
As I said, I'm still learning Spring Boot and Hibernate and I discovered that my problem is a classic cyclic reference. I broke my cyclic reference setting my list of dependents (childs) as write-only, as I don't need this property for read every single time.
I also removed this idHolder redundant property.
Member.class
@Entity @Getter @Setter @NoArgsConstructor @Table(name = "member") public class Member extends Person { @NotNull @Column(name = "member_type") private Integer memberType; @ManyToOne @JoinColumn(name = "id_holder", referencedColumnName = "id") private Member holder; @JsonProperty(access = JsonProperty.Access.WRITE_ONLY) @OneToMany(mappedBy = "holder") private List<Member> dependents; }
And now I know that I could manage this cyclic reference with JsonManagedReference/JsonBackReference too based on which entity I want to handle the relation and which one I want to leave it to the another. And other ways I still need to assimilate.
Answered By - Carlos Messala Oliveira