I have a model like this:
@Entity
[...]
class ParentObject{
[...]
@OneToMany(cascade = CascadeType.ALL, mappedBy= "parentObject", orphanRemoval = true)
private List<Relationship> relationship;
}
and in Relationship entity:
@ManyToOne
@JoinColumn(name="PARENT_OBJECT_ID")
private ParentObject parentObject;
and everything works fine on update and save. Only when I try to create a new ParentObject with new Relationships inside it:
parentObject: {
id: null,
relationship: [
{id:null,
parentObjectId:null,
[...]
}]
}
hibernate doesn't have an id for the ParentObject, so Relationship.parentObject.id is null. Database throws an error saying:
cannot insert NULL into ("MYDB"."RELATIONSHIP"."PARENT_OBJECT_ID")
Any help would be appreciated.
Edit: Here's my service code:
public ParentObjectDto save(ParentObjectDto parentObjectDto) {
ParentObject parentObject = dtoConverter.convert(parentObjectDto, ParentObject.class);
boolean isNewPO = parentObject.getId() == null ? true : false;
parentObject = parentObjectRepository.save(parentObject);
if (isNewPO) {
// This loop ensures that when a new PO is added, the child relationship
// objects are connected with the new parentObject that was just added.
for (Relationship relationship : parentObject.getRelationship()) {
relationship.setParentObject(parentObject);
}
}
return dtoConverter.convert(parentObject, ParentObjectDto.class);
}
the names of course aren't the ones I write here, I just changed them to be more understandable, if I have any spelling mistakes it's from my manual changes :)