How to set a backreference from an @EmbeddedId in JPA

此生再无相见时 提交于 2019-12-01 19:16:25
Gordon Yorke

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

The @EmbeddedId annotation does not allow relationships in the composite identity class. From the EmbeddedId JavaDoc:

Relationship mappings defined within an embedded id class are not supported.

I understand that you want Entity2Identifier to contain the key to the parent, but in your example, you're creating a relationship to the entire object rather than just including the primary key of the parent. Even if this construction worked, you would be establishing the composite key to be not only the primary key of the parent, but the entire state of the parent.

If you're simply looking for an easy way to establish bi-directional relationships, you can do so with the the @OneToOne annotation and the mappedBy attribute:

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

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

@Entity
public class Entity2 {

    @OneToOne
    private Entity1 relationToEntity1;
    ...
}

With this set of annotations, the JPA provider will handle Entity1.relationToEntity2 and Entity2.relationToEntity1 properly as a bi-directional relationship. You might also wish to override the default cascade behavior (none) as well as the default orphan removal behavior (none). See the JavaDoc for more details.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!