I am attempting to persist/merge a brand new object graph through jpa but it seems like the order of persistance is incorrect as it tries to save sub objects who have a constraint on their parent being present.
public class ObjectA implements Serializable {
...
@OneToMany(cascade = CascadeType.ALL, mappedBy = "objectAId")
private List<ObjectB> objectBList;
...
}
and
public class ObjectB implements Serializable {
...
@JoinColumn(name = "OBJECT_A_ID", referencedColumnName = "ID", nullable = false)
@ManyToOne(optional = false)
private ObjectA objectAId;
...
}
I will create a new entity ObjectA and along with several new ObjectB entities and add them to Object A. When i merge ObjectA I get the following:
org.hibernate.PropertyValueException: not-null property references a null or transient value: com.mycompany.data.ObjectB.objectAId
What am I missing or doing wrong?
It's your responsibility to keep both sides of bidirectional relationship in consistent state for objects in memory. In other words, when you add ObjectB to ObjectA.objectBList, you also should make ObjectB.objectAId pointing to the corresponding ObjectA.
Moreover, without optional = false you would be able to persist objects without errors, but the relationship between them wouldn't be persisted if ObjectB.objectAId is null. It happens because Hibernate looks at the state of the owning side of relationship when saving it to the database, and in the case of bidirectional one-to-many relationship owning side is the "many" side (ObjectB)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With