如何在JPA中设置@EmbeddedId的反向引用 [英] How to set a backreference from an @EmbeddedId in JPA

查看:261
本文介绍了如何在JPA中设置@EmbeddedId的反向引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Does someone know if it is possible to establish a backreference from within a JPA @EmbeddedId.

例如,有一个表格的实体

So for example there is an Entity of the Form

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

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

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

And a second entity with a complex embedded Id. One part of this second entity is a reference to its parent entity. Like so:

@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(Implementation is EclipseLink)将这样的构造保存到数据库中我得到了几种形式的例外:

When I try to save such a construct via JPA (Implementation is EclipseLink) to a database I get several exceptions of the form:

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)])

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

Did someone encounter such a problem and has a solution?

推荐答案

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

What you are looking for is a derived Id. If you are using JPA 2.0 then the following will work. You really do not want the whole Parent to be part of the PK, just the parent's 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.
}

这篇关于如何在JPA中设置@EmbeddedId的反向引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆