JPA Mapping OneToMany with partial embedded id child

JPA Mapping OneToMany with partial embedded id child

简单的例子(希望如此)。我在一个 table 中有一个主键(使用序列),该值是子 table 的部分 FK。我看到 Parent 试图用生成的序列保存,但随后我看到一个异常,即在保存 child 时,embeddable 中的 parentId 为 null。用于父级的序列值不会传递给子级。我尝试了很多注释和 mappedBy/join 列名,但没有成功。

任何指点将不胜感激。

public class Parent {
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "audit_seq")
    @SequenceGenerator(name = "audit_seq", allocationSize = 5)
    private Long id;

    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "parent")
    private List<Child> childList = new ArrayList<>();

   //Used to add child record o the parent
    public void addChild(Child child) {
        this.childList .add(child);
        child.setParent(this);
    }
}

@Embeddable
public class ChildId {
   private Long parentId;
   private String name;
}

public class Child {
    @EmbeddedId
    private ChildId id;

    private String myCol;

    @ManyToOne(fetch=FetchType.LAZY)
    @JoinColumn(name = "parentId", insertable = false, updatable = false)
    private Parent parent;

}

我使用了一些注释解决了这个问题:

Parent class:

@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "parent",  orphanRemoval = true)
@PrimaryKeyJoinColumn
private List<Child> childList = new ArrayList<>();

Child class:

@ManyToOne
@MapsId("id")
@JoinColumn(name = "id")
private Parent parent;

现在,在使用适当的序列 ID 保存 parent 时,所有 objects 都会被保留。