【问题标题】:Foreign key mapping inside Embeddable classEmbeddable 类中的外键映射
【发布时间】:2012-04-22 02:55:50
【问题描述】:

我将eclipselink 用于JPA。我有一个实体,它有一个由两个字段组成的复合键。以下是我的可嵌入主键类的字段(成员)。

    @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.

这是否意味着,我不能拥有一个也是外键的键(来自复合键)。是否有替代方法来完成此 ERM?请帮忙。谢谢

【问题讨论】:

    标签: java jpa entity-relationship composite-key embeddable


    【解决方案1】:

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

    【讨论】:

    • 这仅适用于 JPA 1.0,因为 JPA 2.0 允许在 Embeddables 中引用。
    猜你喜欢
    • 2020-05-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-30
    • 1970-01-01
    • 2010-10-31
    • 2021-07-01
    • 2011-08-08
    相关资源
    最近更新 更多