Here is an example of implementing a many-to-many parent-child relationship using JPA, with a Category table and a mapping table, as well as a save API and a fetch API by root ID:
Here is an example of implementing a many-to-many parent-child relationship using JPA, with a Category table and a mapping table, as well as a save API and a fetch API by root ID:
@Entity
public class Category {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
@ManyToMany(cascade = CascadeType.ALL)
@JoinTable(
name = "category_mapping",
joinColumns = @JoinColumn(name = "category_id"),
inverseJoinColumns = @JoinColumn(name = "child_id")
)
private Set<Category> children;
// getters and setters
}
@Entity
public class CategoryMapping {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne
@JoinColumn(name = "category_id")
private Category category;
@ManyToOne
@JoinColumn(name = "child_id")
private Category child;
// getters and setters
}
[check here][1]
https://java-speed.blogspot.com/2023/02/jpa-implemntation-many-to-many-parent.html