I have a one-to-many relation between Parent and Child table. In the parent object I have a
List<Child> setChildren(List<Child> childs)
I also have a foreign key in the Child table. This foreign key is an ID that references a Parent row in database. So in my database configuration this foreign key can not be NULL.
Also this foreign key is the primary key in the Parent table.
So my question is how I can automatically save the children objects by doing something like this:
session.save(parent);
I tried the above but I'm getting a database error complaining that the foreign key field in the Child table can not be NULL. Is there a way to tell JPA to automatically set this foreign key into the Child object so it can automatically save children objects?
Thanks in advance.
Best Answer
Well, there are two things here.
First, you need to cascade the save operation (but my understanding is that you are doing this or you wouldn't get a FK constraint violation during inserts in the "child" table)
Second, you probably have a bidirectional association and I think that you're not setting "both sides of the link" correctly. You are supposed to do something like this:
A common pattern is to use link management methods:
And the code becomes:
References