Reputation: 776
In a JPA entity, I would like to map a column with the same type of entity. Look into the following entity.
@Entity
@Table(name = "Score")
public class Score {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", nullable = false, updatable = false)
private Long id;
@Column(name = "question")
private String question;
@Column(name = "score_count")
private String scoreCount;
@Column(name = "comment")
private String comment;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "parent_id")
private Score parent;
//Getter setter goes here
}
I've added a parent relation of Scope
entity.
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "parent_id")
private Score parent;
Java doesn't throw any exception if I do this. But I want to know, is there any problem to do this in terms of design sense? Is it bad or good practice? If parent is set for same row i.e parent indicates same row, then would it be a loop?
I'm designing some entities now, so it's good to know the reason of doing it or not. Thanks!
Note: I'm using spring data jpa, hibernate and mysql as database
Upvotes: 1
Views: 2375
Reputation: 90417
No problem. It is very common to have this type of self referencing relationship especially when dealing with the hierarchical data.
In the OOP mindset , we would like to work on the abstraction rather than detail as it is easy to understand. So it is even a good parasite if apply this pattern correctly provided that the parent and children entities are really the same abstraction which has some common behaviour in nature . Modelling the parent and the children as the same type allow us to treat them as the same abstraction when writing the logic on them.
If parent is set for same row i.e parent indicates same row, then would it be a loop?
Yes. It will form a loop.That 's why when setting a parent for a children , you should check that the parent cannot be the children itself which should be regarded as one of the business requirements that should be enforced in codes.
Upvotes: 1