Save child objects automatically using JPA Hibernate

Viewed 154042

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.

9 Answers

In JPA @*To* relationships both parent and child entities must be cross assigned before (parent) saving.

If you do not have bidirectional relationship and want to only save/update the the single column in the child table, then you can create JPA repository with child Entity and call save/saveAll or update method.

Note: if you come across FK violations then it means your postman request having primary and foreign key ids is not matching with generated ids in child table , check the ids in your request and child table which your are going to update(they should match/if they don't means you get FK violations) whatever ids generated while saving the parent and child in before transactions, those ids should match in your second call when you try to update the single column in your child table.

Parent:

@Entity
@Table(name="Customer")
public class Customer implements Serializable  {

     @Id
     @GeneratedValue(strategy = GenerationType.IDENTITY)  
     private UUID customerId ;
     
     @OneToMany(cascade = CascadeType.ALL) 
     @JoinColumn(name ="child_columnName", referencedColumnName= 
                "parent_columnName")
     List<Accounts> accountList;
}

Child :

 @Entity
    @Table(name="Account")
    public class Account implements Serializable  {

         @Id
         @GeneratedValue(strategy = GenerationType.IDENTITY)  
         private UUID accountid;
         
        
    }
Related