2012-04-09 104 views
11

我對JPA使用eclipselink。我有一個實體,其中有一個複合鍵由兩個字段組成。以下是我的嵌入式主鍵類的字段(成員)。嵌入類中的外鍵映射

@Embeddable 
    public class LeavePK { 
     @ManyToOne(optional = false) 
     @JoinColumn(name = "staffId", nullable = false) 
     private Staff staff; 
     @Temporal(TemporalType.TIMESTAMP) 
     private Calendar date; 
     //setters and getters 
    } 

我的實體將要舉辦留下相關的人員數據,所以我嘗試要結合員工對象,並離開日期以生產複合鍵。除了我的邏輯之外,它不允許我在嵌入類中使用外鍵映射。當我嘗試使用JPA工具- >從實體生成表時,它給出瞭如下的錯誤,這可以解釋,但我沒有得到它。

org.eclipse.persistence.exceptions.ValidationException 
Exception Description: The mapping [staff] from the embedded ID class [class rs.stapp.entity.LeavePK] is an invalid mapping for this class. An embeddable class that is used with an embedded ID specification (attribute [leavePK] from the source [class rs.stapp.entity.Leave]) can only contain basic mappings. Either remove the non basic mapping or change the embedded ID specification on the source to be embedded. 

這是不是說,我不能有一個鍵(從組合鍵),這也是一個外鍵。有沒有其他方法可以完成這種企業風險管理?請幫忙。謝謝

回答

12

請勿將關係放入ID類中,@IdClass@EmbeddedId之一。 @Embeddable類別可能只包括註釋@Basic,@Column, @Temporal, @Enumerated, @Lob@Embedded。其他的一切都是特定於提供者的語法(例如Hibernate允許這樣做,但由於您使用的是EclipseLink,這是JPA RI,我懷疑這是你想要的)。

下面是一個例子JPA PK/FK映射:

@Entity 
@Table(name = "Zips") 
public class Zip implements Serializable 
{ 
    @EmbeddedId 
    private ZipId embeddedId; 

    @ManyToOne 
    @JoinColumn(name = "country_code", referencedColumnName = "iso_code") 
    private Country country = null; 

    ... 
} 

@Embeddable 
public class ZipId implements Serializable 
{ 
    @Column(name = "country_code") 
    private String countryCode; 

    @Column(name = "code") 
    private String code; 

    ... 
} 

HTH