簡體   English   中英

Hibernate @OneToMany: PSQLException: ERROR: null 列中的值

[英]Hibernate @OneToMany: PSQLException: ERROR: null value in column

我有兩個 dto 和相應的擴展 JpaRepository 的 dao 接口

@Entity
@Table(name = "parent")
@NoArgsConstructor
@AllArgsConstructor
@SequenceGenerator(name = "parentSequence", sequenceName = "parent_id_seq",
        allocationSize = 1)
public class ParentDto implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "parentSequence")
    private Long id;
    
    private String name;

    @OneToMany(mappedBy = "parent", targetEntity = Child.class, cascade = CascadeType.ALL, fetch = FetchType.EAGER)
    private List<ChildDto> children;
}


@Entity
@AllArgsConstructor
@SequenceGenerator(name="childSequence", sequenceName = "child_id_seq", allocationSize=1)
@Table(name = "child")
public class ChildDto {
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "childSequence")
    private Long id;

    private String name;

    @ManyToOne
    @JoinColumn(name = "parent_id", nullable = false)
    private ParentDto parent;
}

public interface ParentDao extends JpaRepository<ParentDto, Long> {
}
public interface ChildDao extends JpaRepository<ChildDto, Long> {
}

我有下一個保存映射到屬性請求的request (ID 應該由 DB 生成)

{“父母”:{“名字”:“鮑勃”,“孩子”:[{“名字”:“鮑勃2”}]}}

執行parentDao.save(request); 並得到例外

Caused by: java.sql.BatchUpdateException: Batch entry 0 insert into child (id, name, parent_id) values (1, "Bob2", NULL) was aborted: ERROR: null value in column "parent_id" violates not-null constraint
詳細信息:失敗行包含 (1, "Bob2", NULL)。 調用 getNextException 以查看批處理中的其他錯誤。 原因:org.postgresql.util.PSQLException:錯誤:“parent_id”列中的 null 值違反了非空約束詳細信息:失敗行包含(1,“Bob2”,NULL)。

您正在將持久性從父級級聯到子級,但子級沒有父級。 除了將孩子添加到父母之外,請確保您還將父母設置在孩子身上。 在聲明雙向關系時保持它們同步很重要

child.setParent(parent);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM