Jsh0s
Jsh0s

Reputation: 599

JPA - Many to One where Child has the Parent id

Sample

Parent class

@OneToMany(mappedBy = "parent")
private List<Child> childs;

Child class

@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "parent_id")
private Parent parent;

I assign the child objects to the parent, then persist the parent.

Problem

The parent and child are being saved, however, the parent field from the child id is saved as null.

Expected

I expected both entities to be saved with a value assigned to the parent field.

Temporal Solution

Well, if I persist the parent without the childs, then assign the childs and merge the parent, it all works, but I was wondering if all that could be done in a single persist.

Upvotes: 0

Views: 1061

Answers (1)

Oleksii Valuiskyi
Oleksii Valuiskyi

Reputation: 2851

I suspect you set one side relation only. You have to set

child.setParent(parent);
parent.getChilds().add(child); // to avoid NullPoinerException childs have to be not null

And then persist child

Upvotes: 1

Related Questions