关于Hibernate多对多拆分为多个一对多的问题.
关于Hibernate多对多拆分为多个一对多的问题.
开发环境为:MyEclipse5.1
数据库:
create table student
(
sid int(8) not null auto_increment,
sname varchar(30) not null default '',
primary key(sid)
)engine=innodb default charset=gbk;
create table teacher
(
tid int(8) not null auto_increment,
tname varchar(30) not null default '',
primary key(tid)
)engine=innodb default charset=gbk;
create table student_teacher_link
(
id int(8) not null auto_increment,
sid int(8),
tid int(8),
primary key(id),
foreign key(sid) references student(sid),
foreign key(tid) references teacher(tid)
)engine=innodb default charset=gbk;
然后通过MyEclipse自动生成功能,生成以下hbm.xml和POJO类文件
学生类
public class Student{
private Integer sid;
private String sname;
private Set studentTeacherLinks = new HashSet(0);
public Student() {}
public Student(String sname) {
this.sname = sname;
}
public Student(String sname, Set studentTeacherLinks) {
this.sname = sname;
this.studentTeacherLinks = studentTeacherLinks;
}
/*一系列set/get方法*/
}
老师类
public class Teacher{
private Integer tid;
private String tname;
private Set studentTeacherLinks = new HashSet(0);
public Teacher() {}
public Teacher(String tname) {
this.tname = tname;
}
public Teacher(String tname, Set studentTeacherLinks) {
this.tname = tname;
this.studentTeacherLinks = studentTeacherLinks;
}
/*一系列set/get方法*/
}
主键关联类
public class StudentTeacherLink{
private Integer id;
private Teacher teacher;
private Student student;
public StudentTeacherLink() {}
public StudentTeacherLink(Teacher teacher, Student student) {
this.teacher = teacher;
this.student = student;
}
/*一系列set/get方法*/
}