OneToMany中間テーブル関連付け
Class
Student
test
@Entity
public class Class {
@Id
@GeneratedValue
@Column(name = "class_id")
private int id;
private String className;
@OneToMany(mappedBy = "myclass", cascade = CascadeType.ALL)
private Set<Student> students = new HashSet<Student>();
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getClassName() {
return className;
}
public void setClassName(String className) {
this.className = className;
}
public Set<Student> getStudents() {
return students;
}
public void setStudents(Set<Student> students) {
this.students = students;
}
}
Student
@Entity
public class Student {
@Id
@GeneratedValue
@Column(name = "student_id")
private int id;
private String studentName;
@ManyToOne(cascade=CascadeType.ALL)
@JoinTable(name = "student_class", joinColumns = @JoinColumn(name = "student_id"), inverseJoinColumns = @JoinColumn(name = "class_id"))
private Class myclass;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
public Class getMyclass() {
return myclass;
}
public void setMyclass(Class myclass) {
this.myclass = myclass;
}
}
test
@Test
public void testOneToManyJoinTable() {
session.beginTransaction();
OneToMany.joinTable.Class c = new OneToMany.joinTable.Class();
c.setClassName("classNmae");
OneToMany.joinTable.Student s1 = new OneToMany.joinTable.Student();
OneToMany.joinTable.Student s2 = new OneToMany.joinTable.Student();
OneToMany.joinTable.Student s3 = new OneToMany.joinTable.Student();
s1.setStudentName("s1");
s2.setStudentName("s1");
s3.setStudentName("s1");
c.getStudents().add(s3);
c.getStudents().add(s2);
c.getStudents().add(s1);
s3.setMyclass(c);
s2.setMyclass(c);
s1.setMyclass(c);
session.save(c);
session.getTransaction().commit();
}