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

Java 如何从JPA中的@EmbeddedId设置反向引用,java,jpa,eclipselink,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 } 以及具有复杂嵌入Id的第二实体。该

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

例如,有一个形式的实体

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

    private Entity1 relationToEntity1;
    //Left out the getters and setters for simplicity
}

以及具有复杂嵌入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.
}

当我试图通过JPA(实现为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)])


是否有人遇到了这样的问题并找到了解决方案?

@EmbeddedId
注释不允许复合标识类中存在关系。从:

不支持在嵌入式id类中定义的关系映射

我知道您希望
Entity2Identifier
包含父对象的键,但在您的示例中,您创建的是与整个对象的关系,而不仅仅是包含父对象的主键。即使这种构造有效,您也将复合键建立为不仅是父级的主键,而且是父级的整个状态

若您只是想寻找一种简单的方法来建立双向关系,那个么可以使用
@OneToOne
注释和
mappedBy
属性:

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

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

@Entity
public class Entity2 {

    @OneToOne
    private Entity1 relationToEntity1;
    ...
}

通过这组注释,JPA提供者将把
Entity1.relationToEntity2
Entity2.relationToEntity1
作为双向关系正确地处理。您可能还希望覆盖默认级联行为(无)以及默认孤立删除行为(无)。有关更多详细信息,请参阅。

您要查找的是派生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.
}

谢谢你的回答。事实上我知道那个。问题是我的主键由多个部分组成,其中一个部分是父实体。这意味着有一些值定义实体,但它仅在parent.OK的上下文中有效。我想我的例子太简单了。父对象实际上有一个复杂的嵌入ID,它也由两个字符串组成。这就是为什么我不能简单地引用它的ID。这也很简单。我已经更新了上面的示例,在实体1上使用EmbeddedId。@MapsId是赢家!太有用了。