I want to persist parent entity with 20 child entities, my code is below
Parent Class
@OneToMany(mappedBy = "parentId")
private Collection<Child> childCollection;
Child Class
@JoinColumn(name = "parent_id", referencedColumnName = "parent_id")
@ManyToOne(optional=false)
private Parent parent;
String jsonString = "json string containing parent properties and child collection"
ObjectMapper mapper = new ObjectMapper();
Parent parent = mapper.readValue(jsonString, Parent.class);
public void save(Parent parent) {
Collection<Child> childCollection = new ArrayList<>() ;
for(Child tha : parent.getChildCollection()) {
tha.setParent(parent);
childCollection.add(tha);
}
parent.setChildCollection(childCollection);
getEntityManager().persist(parent);
}
So if there are 20 child tables then I have to set parent reference in each of them for that I have to write 20 for loops? Is it feasible? is there any other way or configuration where I can automatically persist parent and child?
Fix your Parent class:
@OneToMany(mappedBy = "parent")
mappedBy property should point to field on other side of relationship. As JavaDoc says:
The field that owns the relationship. Required unless the relationship is unidirectional.
Also you should explicitely persist Child entity in cycle:
for(Child tha : parent.getChildCollection()) {
...
getEntityManager().persist(tha);
...
}
As Alan Hay noticed in comment, you can use cascade facilities and let EntityManager automatically persist all your Child entities:
@OneToMany(mappedBy = "parent", cascade = CascadeType.PERSIST)
More details about cascades (and JPA itself) you can find in Vlad Mihalcea's blog.