How to save only a child entity and populate the parentId in the table Using save operation on the child entity

554 Views Asked by At

I would like to understand this basic concept. How do we save the child entity and populate the foreign Key ID in the Child table. I have this situation where Parent Can have many child. But the Child can only have one Parent.

`

Entity
@Table(name = "Child")
@SuppressWarnings("serial")
public class Child implements java.io.Serializable {

@ManyToOne
@JoinColumn(name = "parent_id")
private Parent parent;


}

-------------------------

@Entity
@Table(name = "parent")
@SuppressWarnings("serial")
public class Parent {


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

}



` I am trying to save the child like this below. but its giving me exception that

column "parent" of relation "child" does not exist

Child child = new Child();
child.setParent(parent);
child.setXYZ("XYZ");

childRepository.save(child);

I am trying to save the child entity and expecting it to save the parent_id column automatically. I also tried creating another field in the child entity called

private Long parentId;

and tried to replace this line

child.setParent(parent)

with child.setParentId(parentId);

but nothing is working

1

There are 1 best solutions below

1
hermit On

What you are trying to implement in bidirectional One To Many relationship. And, in bidirectional relationship you should set the both side of the reference.

  1. Initialize the child list in parent entity as: private List<Child> children = new ArrayList<>();

  2. Add an utility method in parent which ensures both side of the references are saved.

    public void addChildren(Children child) {
        children.add(child);
        child.setParent(this);
    }
    
  3. Create parent object, refer child and save.

    Parent parent = new Parent();
    parent.addChildren(new Child());
    parentRepository.save(parent);
    

A good read: https://vladmihalcea.com/the-best-way-to-map-a-onetomany-association-with-jpa-and-hibernate/

If the parent already exists (and lets say has id = 1), and you need to add another child, you can do something like:

Parent parent = parentRepository.findById(id);
parent.addChildren(new Child());
parentRepository.save(parent);