简体   繁体   中英

Hibernate mapping error while inserting child record

I have two entity class as below -

public class Parent {

    @Id
    private Integer parentId;
    private String name;

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

    @Id
    private Integer childId;
    private String name;
    
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "parentId", insertable = false, updatable = true, nullable = false)
    private Parent parent;
}

@RestController
public class ParentController {

    @Autowired
    private ParentRepo repo;

    @GetMapping("/parent")
    public void get() {
        Child c1 = Child.builder().childId(1).name("s1").build();
        Child c2 = Child.builder().childId(2).name("s2").build();
        List<Child> children = new ArrayList<>();
        children.add(c1);
        children.add(c2);
        Parent parent = Parent.builder().parentId(1).name("PARENT")
                .children(children)
                .build();
        Parent savedParent = repo.save(parent);
}
}
Tables -

CREATE TABLE public.parent
(
    parent_id integer NOT NULL,
    name character varying(255) COLLATE pg_catalog."default",
    CONSTRAINT parent_pkey PRIMARY KEY (parent_id)
)WITH (
    OIDS = FALSE
)
TABLESPACE pg_default;

CREATE TABLE public.child
(
    child_id integer NOT NULL,
    name character varying(255) COLLATE pg_catalog."default",
    parent_id integer NOT NULL,
    CONSTRAINT child_pkey PRIMARY KEY (child_id),
    CONSTRAINT fk7dag1cncltpyhoc2mbwka356h FOREIGN KEY (parent_id)
        REFERENCES public.parent (parent_id) MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE NO ACTION
)
WITH (
    OIDS = FALSE
)
TABLESPACE pg_default;

I'm getting error while persisting child record.

Error -

Hibernate: insert into child (name, child_id) values (?, ?) 2022-07-19 23:12:31.727 WARN 20940 --- [nio-8080-exec-2] ohengine.jdbc.spi.SqlExceptionHelper : SQL Error: 0, SQLState: 23502 2022-07-19 23:12:31.727 ERROR 20940 --- [nio-8080-exec-2] ohengine.jdbc.spi.SqlExceptionHelper : ERROR: null value in column "parent_id" violates not-null constraint Detail: Failing row contains (1, s1, null). 2022-07-19 23:12:31.728 INFO 20940 --- [nio-8080-exec-2] ohejbinternal.AbstractBatchImpl : HHH000010: On release of batch it still contained JDBC statements 2022-07-19 23:12:31.754 ERROR 20940 --- [nio-8080-exec-2] oaccC[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint [parent_id]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement] with root cause

org.postgresql.util.PSQLException: ERROR: null value in column "parent_id" violates not-null constraint Detail: Failing row contains (1, s1, null).

Not sure how hibernate will pick and assign the foreign key to child.

You have to set the bidirectional relationship first

public class Parent {

     @Id
     private Integer parentId;
     private String name;

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

     public void addChild(Child child) {
           this.children.add(child);
           child.setParent(this);
     }
}

and add the children via that method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM