teoberk
teoberk

Reputation: 11

Using cascades with mappedBy in Hibernate

I have two classes teacher and course. teacher can have multiple courses. I want to use all cascades except Remove.

public Teacher {

    @OneToMany(mappedBy = "teacher",cascade = {CascadeType.MERGE,CascadeType.PERSIST,CascadeType.DETACH,CascadeType.MERGE})
    private List<Course> courses;
}
public class Course {
    ....
    @ManyToOne(cascade = {CascadeType.PERSIST,CascadeType.MERGE,CascadeType.DETACH,CascadeType.REFRESH})
    @JoinColumn(name="teacher_id")
    private Teacher teacher;
}

and than create objects to save them in another main class.

    List<Course> l = new ArrayList<>();
    l.add(course1);
    l.add(course2);
    teacher.setCourses(l);

    SessionFactory sf = new Configuration().configure().addAnnotatedClass(Teacher.class).
    addAnnotatedClass(Course.class).buildSessionFactory();
    Session session = sf.getCurrentSession();

    try {
        session.beginTransaction();
        session.save(teacher);
        session.getTransaction().commit();

but it does not save courses. ok maybe mappedBy things are not saved automatically and i should write session.save(course), but then why should i write cascade types in Teacher, if it is not doing nothing automatically?

Upvotes: 1

Views: 240

Answers (1)

johnnyutts
johnnyutts

Reputation: 1452

You have specified a bidirectional relationship, but are only adding courses to teacher. Your course entities have no teacher so need to be added before persisting teacher.

List<Course> l = new ArrayList<>();
l.add(course1);
l.add(course2);
teacher.setCourses(l);

course1.setTeacher(teacher)
course2.setTeacher(teacher)

In the above relationship you can think of Teacher as the parent and Courses as the children. In which case it is only recommended to cascade from parent to child so remove your cascades in Course entity. That way you always know which way the cascades are going

public class Course {
    ....
    @ManyToOne
    @JoinColumn(name="teacher_id")
    private Teacher teacher;
}

Upvotes: 0

Related Questions