@OneToMany and composite primary keys?

前端 未结 9 1712
温柔的废话
温柔的废话 2020-12-01 03:31

I\'m using Hibernate with annotations (in spring), and I have an object which has an ordered, many-to-one relationship which a child object which has a composite primary key

9条回答
  •  温柔的废话
    2020-12-01 04:13

    You should incorporate the ParentObject reference just into ChildObject.Pk rather than map parent and parentId separately:

    (getters, setters, Hibernate attributes not related to problem and member access keywords omitted)

    class ChildObject { 
        @Embeddable
        static class Pk {
            @ManyToOne...
            @JoinColumn(name="parentId")
            ParentObject parent;
    
            @Column...
            String name...
            ...
        }
    
        @EmbeddedId
        Pk id;
    }
    

    In ParentObject you then just put @OneToMany(mappedBy="id.parent") and it works.

提交回复
热议问题