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?