@OneToMany and composite primary keys?

前端 未结 9 1744
温柔的废话
温柔的废话 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:15

    It seems that you got pretty close, and I am trying to do the same thing in my current system. I started with the surrogate key but would like to remove it in favor of a composite primary key consisting of the parent's PK and the index in the list.

    I was able to get a one-to-one relationship that shares the PK from the master table by using a "foreign" generator:

    @Entity
    @GenericGenerator(
        name = "Parent",
        strategy = "foreign",
        parameters = { @Parameter(name = "property", value = "parent") }
    )
    public class ChildObject implements Serializable {
        @Id
        @GeneratedValue(generator = "Parent")
        @Column(name = "parent_id")
        private int parentId;
    
        @OneToOne(mappedBy = "childObject")
        private ParentObject parentObject;
        ...
    }
    

    I wonder if you could add the @GenericGenerator and @GeneratedValue to solve the problem of Hibernate not assigning the parent's newly acquired PK during insertion.

提交回复
热议问题