Issue
I have two entities which are related in a parent child manner, via a @OneToMany bidirectional relationship in spring data JPA.
The underlying tables are populated via an external feed, and there are occasions when we receive the child before the parent. The primary/foreign keys are used from the incoming feed so we know what they will be ahead of time (although we have no enforced fk constraints on the db). The data will eventually be consistent.
Is there a way to insert a child entity with a reference to the parent key, even though the parent does not yet exist.
We are using the latest version of Spring data jpa with hibernate as our provider.
Solution
Is there a way to insert a child entity with a reference to the parent key, even though the parent does not yet exist.
Well, one way to do it would be to add a native SQL query to your ChildEntityRepository
, something like (.persistWhenParentNotAvailable()
).
When you know that the parent data is not available at a given point in this, you use this method to save the data.
I think you can also try to manually give to the child a parent object with only the ID field set and make sure to NOT
have cascading configured for this child->parent
relationship.
Answered By - Arthur Klezovich
Answer Checked By - David Marino (JavaFixing Volunteer)