如何在JPA中设置@EmbeddedId的反向引用

ali*_*ali 5 java jpa eclipselink

有人知道是否可以在JPA中建立反向引用@EmbeddedId.

例如,有一个表格的实体

@Entity
public class Entity1 {
    @Id
    @GeneratedValue
    private String identifier;

    private Entity1 relationToEntity1;
    //Left out the getters and setters for simplicity
}
Run Code Online (Sandbox Code Playgroud)

第二个具有复杂嵌入式Id的实体.第二个实体的一部分是对其父实体的引用.像这样:

@Entity
public class Entity2 {
    @EmbeddedId private Entity2Identifier id;
    //Left out the getters and setters for simplicity.
}

@Embedabble
public class Entity2Identifier {
    private String firstPartOfIdentifier;
    private Entity1 parent;
    //Left out the getters and setters for simplicity.
}
Run Code Online (Sandbox Code Playgroud)

当我尝试通过JPA(Implementation is EclipseLink)将这样的构造保存到数据库时,我得到了几个例外:

Exception [EclipseLink-93] (Eclipse Persistence Services - 1.1.0.r3639-SNAPSHOT): 
org.eclipse.persistence.exceptions.DescriptorException
Exception Description: The table [ENTITY1] is not present in this descriptor.
Descriptor: RelationalDescriptor(test.Entity2 --> [DatabaseTable(ENTITY2)])
Run Code Online (Sandbox Code Playgroud)

有人遇到这样的问题并有解决方案吗?

Gor*_*rke 4

您正在寻找的是派生 ID。如果您使用 JPA 2.0,则以下内容将起作用。您确实不希望整个父级成为 PK 的一部分,而只是父级 PK 的一部分。

@Entity
public class Entity1 {
    @EmbeddedId
    private ParentId identifier;

    @OneToOne(mappedBy="relationToEntity1")
    private Entity2 relationToEntity2;

    //Left out the getters and setters for simplicity
}

@Entity
public class Entity2 {
    @EmbeddedId private Entity2Identifier id;
    //Left out the getters and setters for simplicity.

    @MapsId("parentId")
    @OneToOne
    private Entity1 parent;

}

@Embedabble
public class Entity2Identifier {
    private String firstPartOfIdentifier;
    private ParentId parentId;
    //Left out the getters and setters for simplicity.
}
Run Code Online (Sandbox Code Playgroud)