Reputation: 2062
I know the question can be simple, but, anyhow, I want to implement simple parent-child relations in one table using hibernate:
Parent
| \
Child1 Child2
| |
Junior1 Junior2
so it should looks like the following in the database:
id | name | parent_id
1 Parent null
2 Child1 1
3 Child2 1
4 Junior1 2
5 Junior2 3
In case of @Entity class:
@Entity
@Table(name = "PARENT_CHILD")
public class ParentChild {
@Id
@Column(name = "ID", nullable = false, unique = true)
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
@Column(name = "NAME", nullable = false)
private String name;
private String parentId; // <------ how this should be mapped?
}
What is the best practice on how i should map the parentId or make the following another way? Thank you
Upvotes: 0
Views: 38
Reputation: 414
Normally, you can create a relational mapping to map within StateEntity
@ManyToOne
@JoinColumn(name="parent_id", referencedColumnName="id")
private ParentChild parent;
in case it is a parent, then its parent can be null.
If in your project, due to performance there is case you want to load parent_id only instead of the whole ParchentChild parent instance. You can add column mapping as well
@Column(name="parent_id", insertable=false, updatable=false)
private int parentId;
insertable=false, updatable=false is too make sure your system can update parent_id through @ManyToOne field only
Upvotes: 1