Define the level when using @ManyToOne that relate the same entity

94 views Asked by At

I have an object that can be child of itself, in a way that it generates a tree of objects, for exemple an article could be the composition of many other articles, so i'm using a @ManyToOne to relate the article to itself, the tree of 4 articles should look like this:

article A (lvl 1) --> article B (lvl 2) --> article C (lvl 3) --> article D (lvl 4)

@Entity
public class Article implements Serializable {

    @ManyToOne
    @JoinColumn(name = "article_father", referencedColumnName = "id")
    private Article articleFather;

    @Column(name = "level")
    private Integer level;

}

Now my problem is when i want to remove the father of article B, is there any way with jpa to refresh the levels of article B and C and D, so that i would have two trees :

article A (lvl 1)

article B (lvl 1) --> article C (lvl 2) --> article D (lvl 3)

1

There are 1 answers

0
Zhurov Konstantin On

If I right you need tree.

My example:

@Entity(name = "geography")
@Table(schema = "TEST", name = "GEOGRAPHY")
public class Geography {

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

@Column(name = "NAME")
private String name;

@ManyToOne
@JoinColumn(name = "parent_id")
@JsonIgnore
private Geography parent;

@OneToMany(mappedBy = "parent")
@JsonIgnore
private Set<Geography> setElements = new HashSet<Geography>();
...
}

level - count of parents