Reputation: 4464
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 :)
Upvotes: 1
Views: 687
Reputation: 24433
Looking at the code, the problem might be when isNewPO
is true you first save the PO and after that you set that parent object to the relationship. This means that at the time of persisting PO, relationships don't have their PO set, leading to NULL
being inserted in PARENT_OBJECT_ID
column (relationships are also persisted at this time because of cascade = CascadeType.ALL
).
To resolve this, either move parentObject = parentObjectRepository.save(parentObject);
after the loop, or wire up PO and its relationships in dtoConverter.convert()
.
Upvotes: 1