Embeddable类中的外键映射

Aha*_*med 12 java entity-relationship jpa composite-key embeddable

我使用eclipselinkJPA.我有一个实体,它有一个由两个字段组成的复合键.以下是我的可嵌入主键类'字段(成员).

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

我的实体将保留与员工相关的休假数据,因此我尝试将员工对象和离开日期结合起来以生成组合键.除了我的逻辑,它不允许我在embeddable类中有一个外键映射.当我尝试使用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.
Run Code Online (Sandbox Code Playgroud)

这是否意味着,我不能拥有一个也是外键的密钥(来自复合密钥).有没有其他方法来完成此ERM?请帮忙.谢谢

Kaw*_*awu 15

不要将关系放入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;

    ...
}
Run Code Online (Sandbox Code Playgroud)

HTH

  • 这仅适用于 JPA 1.0,因为 JPA 2.0 允许在 Embeddable 中进行引用。 (2认同)