Hibernate / JPA-在保存父实体时,从父表到子表插入生成的非pk / fk序列生成的列值

时间:2019-07-12 10:52:56

标签: hibernate spring-mvc jpa-2.0 one-to-many cascade

我有一个父实体,该实体具有一个ID列(ID)和非主要但唯一的列(KEY_ID)。该KEY_ID是通过序列在Oracle数据库中自动生成的。 我有一个具有相同KEY_ID列的子实体,并且它是一个非主键列。 我在父实体和子实体之间有一个oneTomany关联。 因此,当我保存父项时,它会在子表中以及预期的情况下插入一条记录。到目前为止我还不错。但是,我也想将父表中KEY_ID的值保存到子表中的KEY_ID列。我不确定,是否可以实现。任何帮助将不胜感激,因为我在此上花费了大量时间。

@Entity
@Table(name = "PARENT")
@SequenceGenerator(name = "SEQ_GENERATOR1", sequenceName = "SEQNAME1")
public class Parent {

    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "SEQ_GENERATOR1")
    @Id
    @Column(name = "PARENT_ID")
    private Long id;

    @Column(name = "KEY_ID") // This column is a sequence in the table handled in Oracle.
    private Long keyId; // want to send this column value to the child entity when saving parent entity.

    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "parent")
    private Set<Child> children;
    ...
}

@Entity
@Table(name = "CHILD")
@SequenceGenerator(name = "SEQ_GENERATOR2", sequenceName = "SEQNAME2")
public class Child  {

    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "SEQ_GENERATOR2")
    @Id
    @Column(name = "CHILD_ID")
    private Long id;

    @Column(name = "KEY_ID")
    private Long keyId; 

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "PARENT_ID", nullable=false)
    private Parent parent;
    ...
}```

0 个答案:

没有答案