示例:一个老师(Teacher)有多个学生(Student),一个学生有多个老师。
public class Teacher { private Integer id; private String name; private Set<Student> students = new HashSet<Student>(); // getter and setter }
public class Student { private Integer id; private String name; private Set<Teacher> teachers = new HashSet<Teacher>(); // getter and setter }
用XML映射
<hibernate-mapping package="org.monday.hibernate4.domain"> <class name="Teacher" table="tbl_teacher"> <id name="id"> <generator class="identity" /> </id> <property name="name" /> <set name="students" table="tbl_student_teacher"> <key column="teacher_id" /> <many-to-many class="Student" column="student_id" /> </set> </class> </hibernate-mapping>
<hibernate-mapping package="org.monday.hibernate4.domain"> <class name="Student" table="tbl_student"> <id name="id"> <generator class="identity" /> </id> <property name="name" /> <set name="teachers" table="tbl_student_teacher" inverse="true"> <key column="student_id" /> <many-to-many class="Teacher" column="teacher_id" /> </set> </class> </hibernate-mapping>
用@Annotation映射
@Entity @Table(name = "tbl_teacher") public class Teacher { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; private String name; @ManyToMany @JoinTable(name = "tbl_student_teacher", joinColumns = @JoinColumn(name = "teacher_id"), inverseJoinColumns = @JoinColumn(name = "student_id")) private Set<Student> students = new HashSet<Student>(); // getter and setter }
@Entity @Table(name = "tbl_student") public class Student { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; private String name; @ManyToMany(mappedBy = "students") private Set<Teacher> teachers = new HashSet<Teacher>(); // getter and setter }
@ManyToMany中增加mappedBy属性的实体将不再控制关联关系
测试代码
Student s = new Student(); s.setName("terry"); Teacher t = new Teacher(); t.setName("mary"); t.getStudents().add(s); s.getTeachers().add(t); session.save(t); session.save(s);
SQL schema
Hibernate: create table tbl_student ( id integer not null auto_increment, name varchar(255), primary key (id) ) Hibernate: create table tbl_student_teacher ( teacher_id integer not null, student_id integer not null, primary key (teacher_id, student_id) ) Hibernate: create table tbl_teacher ( id integer not null auto_increment, name varchar(255), primary key (id) ) Hibernate: alter table tbl_student_teacher add index FK2BB635DB556D6E8 (teacher_id), add constraint FK2BB635DB556D6E8 foreign key (teacher_id) references tbl_teacher (id) Hibernate: alter table tbl_student_teacher add index FK2BB635DA4BB8C48 (student_id), add constraint FK2BB635DA4BB8C48 foreign key (student_id) references tbl_student (id) Hibernate: insert into tbl_teacher (name) values (?) Hibernate: insert into tbl_student (name) values (?) Hibernate: insert into tbl_student_teacher (teacher_id, student_id) values (?, ?)