有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java JPA:在父类和子类中都有@IdClass的子类中没有插入外键

我有一个父母有复合PK(id+序列号)。 子级还有一个PK(id+serial_no+属性),其中FK是(id+serial_no)

注意:我使用了@IdClass而不是@EmbeddedId,就像在我的父项中一样,我有id要从序列生成(我在stackoverflow上读到sequencegenerator不使用EmbeddedId)

问题:

Caused by: oracle.jdbc.OracleDatabaseException: ORA-01400: cannot insert NULL into ("schema_name"."child"."id")

下面是我的保存逻辑

Parent parent = new Parent();
parent.setSerialNo(0L);
//Note I don't want to set the Id as its supposed to be generated by the sequence

Child child = new Child();
child.setAttribute("abc");
//so in the below line am setting parent in child class
child.setParent(parent);
//note in the child am not setting the id and serial_no coz i want it to come from parent

repository.save(parent);
// I am expecting the cascade so that both the parent and child get saved

以下是我的实体代码:

@Entity
@Table(name = "parent")
@IdClass(ParentPK.class)
public class Parent implements Serializable {
     @Id
    @Column(name = "id", nullable = false)
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator")
    @SequenceGenerator(name = "sequenceGenerator", sequenceName="o_seq", allocationSize=1)
    private Long id;
    
    @Id
    @Column(name="serial_no")
    Long serialNo; 

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

@Entity
@Table(name="child")
@IdClass(ChildPK.class)
public class Child implements Serializable{

    @Id
    @Column(name="id")
    Long id;
    
    @Id
    @Column(name="serial_no")
    Long serialNo;
    
    @Id
    @Column(name="attribute")
    String attribute;

    @JoinColumns(value = {
            @JoinColumn(name = "id", referencedColumnName = "id", insertable = false, updatable = false),
            @JoinColumn(name = "serial_no", referencedColumnName = "serial_no", insertable = false, updatable = false)
        })
    @JsonBackReference
    @ManyToOne(fetch=FetchType.LAZY, optional=true)
    private Parent parent;
}

非常感谢


共 (0) 个答案