Ответ 1
Если вы добавляете дополнительные поля в связанную таблицу (STUDENT_COURSE), вам нужно выбрать подход в соответствии с ответом скаффмана или другим, как показано ниже.
Существует подход, в котором связанная таблица (STUDENT_COURSE) ведет себя как @Embeddable в соответствии с:
@Embeddable
public class JoinedStudentCourse {
// Lets suppose you have added this field
@Column(updatable=false)
private Date joinedDate;
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name="STUDENT_ID", insertable=false, updatable=false)
private Student student;
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name="COURSE_ID", insertable=false, updatable=false)
private Course course;
// getter and setter
public boolean equals(Object instance) {
if(instance == null)
return false;
if(!(instance instanceof JoinedStudentCourse))
return false;
JoinedStudentCourse other = (JoinedStudentCourse) instance;
if(!(student.getId().equals(other.getStudent().getId()))
return false;
if(!(course.getId().equals(other.getCourse().getId()))
return false;
// ATT: use immutable fields like joinedDate in equals() implementation
if(!(joinedDate.equals(other.getJoinedDate()))
return false;
return true;
}
public int hashcode() {
// hashcode implementation
}
}
Итак, вы будете иметь и в классах ученика и курса
public class Student {
@CollectionOfElements
@JoinTable(
[email protected](name="STUDENT_COURSE"),
[email protected](name="STUDENT_ID")
)
private Set<JoinedStudentCourse> joined = new HashSet<JoinedStudentCourse>();
}
public class Course {
@CollectionOfElements
@JoinTable(
[email protected](name="STUDENT_COURSE"),
[email protected](name="COURSE_ID")
)
private Set<JoinedStudentCourse> joined = new HashSet<JoinedStudentCourse>();
}
помните: класс @Embeddable имеет свой жизненный цикл, привязанный к классу обладающих сущностей (как студенту, так и курсу), поэтому позаботьтесь об этом.
Совет: команда Hibernate поддерживает эти два подхода (@OneToMany (ответ скаффмана) или @CollectionsOfElements) из-за некоторых ограничений в сопоставлении @ManyToMany - каскадной операции.
С уважением,