Persistence in JPA Cascade

Asked

Viewed 257 times

1

I’m trying to perform a cascade persistence using JPA.

I have the entity: Course and Module

  • 1 Course can have several 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 that the moment that the Course is saved it saves all the "children - Module". As it is today, the two are persisting in the correct way. However in the table module the field id_course is turning out to be null.

1 answer

2


Probably because Course is null

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

Fill it before saving

for (Module  m : course.getModules()) {
    m.setCourse(course);
}
  • Great Weslley I believe that’s exactly it... I’m filling this object with GSON. After this procedure, I will try to carry out this additional step to see if it solves the problem.

  • Thank you very much friend, it worked perfectly!!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.