2012-03-14 20 views
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

回答

2

有沒有什麼好的方法可以共享公共字段映射?

MappedSuperclass正是這樣的工具。

它甚至可能聲明@Id protected Long id; 在擴展類上留下@TableGenerator和@GeneratedVAlue?

不,這是不可能的。