多对多(teacher - student)
在操作和性能方面都不太理想,所以多对多的映射使用较少,实际使用中最好转换成一对多的对象模型;Hibernate会为我们创建中间关联表,转换成两个一对多。
<set name="teacher" table="teacher_student">
<key column="teacher_id"/>
<many-to-many class="Student" column="student_id"/>
</set>
teacher
private int id;
private String name;
private Set<Student> student;
student
private int id;
private String name;
private Set<Teacher> teacher;
<hibernate-mapping>
<class name="com.huawei.domain.Teacher">
<id name="id" type="java.lang.Integer">
<column name="id" />
<generator class="native" />
</id>
<property name="name" type="java.lang.String">
<column name="name" length="5" not-null="false" />
</property>
<set name="student" table="teacher_student">
<key column="teacher_id"></key>
<many-to-many class="com.huawei.domain.Student" column="student_id"></many-to-many>
</set>
</class>
</hibernate-mapping>
<hibernate-mapping>
<class name="com.huawei.domain.Student">
<id name="id" type="java.lang.Integer">
<column name="id" />
<generator class="native" />
</id>
<property name="name" type="java.lang.String">
<column name="name" length="5" not-null="false" />
</property>
<set name="teacher" table="teacher_student">
<key column="student_id"></key>
<many-to-many class="com.huawei.domain.Teacher" column="teacher_id"></many-to-many>
</set>
</class>
</hibernate-mapping>
测试:
Session s = null;
Transaction tx = null;
try {
s = HibernateSessionFactory.getSession();
tx = s.beginTransaction();
Set<Teacher> tt = new HashSet<Teacher>();
Teacher t1 = new Teacher();
t1.setName("t1");
tt.add(t1);
Teacher t2 = new Teacher();
t2.setName("t2");
tt.add(t2);
Set<Student> ss = new HashSet<Student>();
Student s1 = new Student();
s1.setName("s1");
ss.add(s1);
Student s2 = new Student();
s2.setName("s2");
ss.add(s2);
t1.setStudent(ss);
t2.setStudent(ss);
s.save(t1);
s.save(t2);
s.save(s1);
s.save(s2);
tx.commit();
} catch (HibernateException e) {
e.printStackTrace();
}finally{
if(s != null){
HibernateSessionFactory.closeSession();
}
}