Reputation: 4914
In JPA is there any way to model the following kind of relationship?
PERSON INT id PKEY VARCHAR name CHILD INT parentId FKEY(PERSON->id) INT nameId FKEY(PERSON->id)
Where parentId
is a many-to-one relationship and nameId
is a one-to-one relationship. So, essentially, parentId
and nameId
would create a compound primary key in CHILD?
Thanks!
Upvotes: 0
Views: 162
Reputation: 1072
You can create an entity for your scenario. But the table design should be the nameId should be the primary key of the child table and if you have trouble for creating entity class then in NetBeans IDE or Eclipse IDE there is an option for 'Entity class from table' for the entity class creation.
Upvotes: 0
Reputation: 80633
I would rename nameId
to childId
. Logically you have a relationship between a person and its children. Where each child is a person itself. With the model you currently have there is no reason to have a separate child
table, but let's assume you will add distinct attributes later on. I would model the relationship using inheritance and aggregation:
@Entity
@Table(name="PERSON")
@Inheritance(strategy=InheritanceType.JOINED)
public class Person implements Serializable {
@Id
private Integer id;
private String name;
@OneToMany(mappedBy = "parent")
private List<Child> children;
}
@Entity
@Table(name="CHILD")
@PrimaryKeyJoinColumn(name="nameId", referencedColumnName = "id")
private class Child extends Person implements Serializable {
@ManyToOne
@JoinColumn(name = "parentId", referencedColumnName = "id")
private Person parent;
}
This is sample code, typed verbatim, you will have to error check it yourself. But it's a starting point.
Upvotes: 1