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
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.Initialize the child list in parent entity as:
private List<Child> children = new ArrayList<>();Add an utility method in parent which ensures both side of the references are saved.
Create parent object, refer child and save.
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: