1
我有兩個或多個表相互類似。JPA通過擴展而無需繼承來重複使用代碼
PARENT
ID | PK
NAME | VARCHAR
CHILD
ID |PK
NAME | VARCHAR
AGE | INT
這不是@Inheritance
的情況,因爲它們是獨立的實體,並通過@OneToMany
或@ManyToOne
彼此相關。
我爲對方創建實體類。
@Entity
public class Parent {
@Id
private Long id;
private String name;
@ManyToOne(mappedBy = "parent")
private Collection<Child> children;
}
@Entity
public class Child {
@Id
private Long id;
private String name;
private int age;
@OneToMany
private Parent parent;
}
有沒有什麼好的方法來分享常見的字段映射?
// @MappedSuperclass // is this what it is exactly for?
public abstract class Base {
// @Id protected Long id; // @@?
@Column(name = "name", nullable = false)
private String name;
}
@Entity
public class Parent extends Base {
@Id
@TableGenerator(...)
@GeneratedValue(...)
protected Long id;
@ManyToOne(mappedBy = "parent")
private Collection<Child> children;
}
@Entity
public class Child extends Base {
@Id
@TableGenerator(...)
@GeneratedValue(...)
protected Long id;
private int age;
@OneToMany
private Parent parent;
}
可以嗎?
是否甚至有可能在基礎上聲明@Id protected Long id;
,而在擴展類上留下@TableGenerator
和@GeneratedVAlue
?