I have three tables one to hold student information, second which holds class information. Third is to associate the student and class studentclass table
The entities and relationships are given below
class Student
{
@Id
@Column(name="STUDENT_ID")
long studentId;
@OneToMany(cascade=CascadeType.ALL,mappedBy="student")
Set<StudentClass> studentClasses
}
class Class
{
@Id
@Column(name="CLASS_ID")
long classId;
@OneToMany(cascade=CascadeType.ALL,mappedBy="class")
Set<StudentClass> studentClasses
}
class StudentClass
{
@Id
@Column(name="STUDENT_CLASS_ID")
long studentClassid;
@ManyToOne
@JoinColumn(name="STUDENT_ID")
private Student student;
@ManyToOne(cascade=CascadeType.ALL)
@JoinColumn(name="CLASS_ID")
private Class class;
}
class persist{
public void persist(){
Student student1 = new Student();
Class class1 = new Class();
session.save(class1);
StudentClass studentClass = new StudentClass();
studentClass.setClass(class1);
studentClass.setStudent(student1);
student1.getStudentClasses().add(studentClass);
session.save(student1);
session.getTransaction().commit();
}
}
The above persistence logic works fine as I save class1 separately and finally student class. But if I try to do save student1 alone the class1 is not getting saved? If the answer is class and students are not directly related then how retrieval gets all the classes when I try to fetch a student