Hibernate @OneToMany: PSQLException: ERROR: null value in column

Viewed 41

I have two dtos and corresponding dao interfaces which extend JpaRepository

@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> {
}

I have the next request to save mapped to property request (ids should be generated by DB)

{ "parent": { "name": "Bob", "children": [{ "name": "Bob2" }] } }

Executing parentDao.save(request); and getting exception

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
Detail: Failing row contains (1, "Bob2", NULL). Call getNextException to see other errors in the batch. Caused by: org.postgresql.util.PSQLException: ERROR: null value in column "parent_id" violates not-null constraint Detail: Failing row contains (1, "Bob2", NULL).

1 Answers

You are cascading persistence from the parent to the child, but the child has no parent. As well as adding a child to the parent make sure you also set the parent on the child. It's important to keep them in sync when declaring bidirectional relationships

child.setParent(parent);
Related