有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

可嵌入类内的java外键映射

我正在用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?请帮忙。谢谢


共 (1) 个答案

  1. # 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;
    
        ...
    }