How to set a backreference from an @EmbeddedId in JPA

后端 未结 2 430
天命终不由人
天命终不由人 2021-01-18 22:52

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

<

相关标签:
2条回答
  • 2021-01-18 23:15

    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.
    }
    
    0 讨论(0)
  • 2021-01-18 23:28

    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.

    0 讨论(0)
提交回复
热议问题