本文共 2288 字,大约阅读时间需要 7 分钟。
package cn.edu.hpu.many2many;import java.util.HashSet; import java.util.Set;public class Student { private int id; private String name; private SetTeacher.java:teachers=new HashSet (); public Set getTeachers() { return teachers; } public void setTeachers(Set teachers) { this.teachers = teachers; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
package cn.edu.hpu.many2many;import java.util.HashSet;import java.util.Set;import cn.edu.hpu.many2many.Student;public class Teacher { private int id; private String name; private Set配置文件: Student.hbm.xml:students=new HashSet (); //选择set的原因是因为,set互相之间不会有重复的 //跟数据库模型比较匹配 public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Set getStudents() { return students; } public void setStudents(Set students) { this.students = students; } }
Teacher.hbm.xml:
在hibernate.cfg.xml中配置:
生成的sql语句: create table t_s ( student_id integer not null, teacher_id integer not null, primary key (teacher_id, student_id) ) create table xm_student ( id integer not null auto_increment, name varchar(255), primary key (id) ) create table xm_teacher ( id integer not null auto_increment, name varchar(255), primary key (id) ) alter table t_s add index FK1BF687B5893C2 (teacher_id), add constraint FK1BF687B5893C2 foreign key (teacher_id) references xm_teacher (id) alter table t_s add index FK1BF686ABD4922 (student_id), add constraint FK1BF686ABD4922 foreign key (student_id)
references xm_student (id)
转载请注明出处: