Save an entity and all its related entities in a single save in spring boot

You would have to add a small piece of code which would populate each CustomReportActivity within the CustomReport instance. Only then the persistence provide can successfully perform the cascade save operation:

public CustomReport createCustomReport(CustomReport customReport) {
   customReport.getCustomReportActivitySet.forEach((activity) -> {
      activity.setCustomReport(customReport);
   });

   return customReportRepository.save(customReport);
}

The bottom line is that the dependencies have to be set on both sides of the relationship.


Try this sample, in my case it worked as expected, child entities are saved automatically in a single save operation with creating relations to a parent entity:

@Entity
public class CustomReport {
    @Id
    private Long id;

    @JoinColumn(name = "reportId")
    @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
    private Set<CustomReportActivity> activities;
}

@Entity
public class CustomReportActivity {
    @Id
    private Long id;
    private Long reportId;
}