How to define @OneToMany in parent entity when child has composite PK?

前端 未结 1 1839
攒了一身酷
攒了一身酷 2020-12-22 02:48

My Parent class has two child classes: Child and ParentHobby. The Child class has a singular PK and the @OneToMany mapp

相关标签:
1条回答
  • 2020-12-22 03:24

    You need to use a derived identity.

    ParentHobbyPK should look like this:

    @Embeddable
    public class ParentHobbyPK {
        @Column(name="HOBBY_ID")
        private String hobbyID;
        private long parentID; // corresponds to the PK type of Parent
    }
    

    ParentHobby should look like this (the important thing being the @MapsId annotation):

    @Entity
    @Table(name="PARENT_HOBBY")
    public class ParentHobby {
        @EmbeddedId
        private ParentHobbyPK id;
    
        @MapsId("parentID") // maps parentID attribute of the embedded ID
        @ManyToOne(optional = true)
        @JoinColumn(name = "PARENT_ID", referencedColumnName = "PARENT_ID", insertable = true, updatable = true)
        private Parent parent;
    
        ...
    }
    

    Derived identity is discussed in JPA 2.1 spec, section 2.4.1.

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