JPA Cascade Persistence

1

I'm trying to perform a cascading persistence using JPA.

I have the entity: Course and Module

  • 1 Course can have multiple Module

    @Entity(name = "course")
    
    public class Course extends BaseEntity {
    
    private static final long serialVersionUID = 1L;
    
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id_course")
    private Long idCourse;
    
    @SerializedName("Modules")
    @OneToMany(mappedBy = "course", cascade = CascadeType.ALL, orphanRemoval = false)
    private List<Module> modules;
    
  • 1 Module can have only one Course

    @Entity(name = "module")
    public class Module extends BaseEntity {
    
    private static final long serialVersionUID = 1L;
    
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id_module")
    private Long idModule;
    
    @OneToOne
    @JoinColumn(name = "id_course")
    private Course course;
    

I want the Course to be saved when it saves all "children - Module". As you are today, you are persistently persisting. However in the module table the id_course field is getting null.

    
asked by anonymous 09.05.2018 / 18:51

1 answer

2

Probably because the course is null

@OneToOne(cascade= {{CascadeType.DETACH})
@JoinColumn(name = "id_course")
private Course course;

Fill it out before saving

for (Module  m : course.getModules()) {
    m.setCourse(course);
}
    
09.05.2018 / 19:38