多对多,必须有一张关系表来维持关系
数据库student,teacher student_teacher 三张表
但是在pojo中只需要建立student和teacher两个类,除非关系表也代表某种业
务(比如订单中,除了产品还会记录价格,数量等),但是这时候性质也就变了,成了两个一对多
...好好想想...
//分别Set
public class Student {
private Integer id;
private String name;
private Set<Teacher> teachers;
} public class Teacher {
private Integer id;
private String name;
private Set<Student> students;
}
xxx.hbm.xml配置
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.kaishengit.pojo"> <class name="Teacher" table="teacher">
<id name="id">
<generator class="native"/>
</id> <property name="name"/>
<!-- name="students"属性名,table="student_teacher"关系表名,这里的
order-by表示查询的顺序,指查询关系表中id的倒序-->
<set name="students" table="student_teacher" inverse="true" order-by="id desc" >
<!-- tid表示teacher在关系表中的外键名 -->
<key column="tid"/>
<!-- class="Student"指定Set集合中的类是Student,column="sid"关系表中的外键
order-by表示查询的顺序,指查询Student中id的倒序-->
<many-to-many class="Student" column="sid" order-by="id desc,name asc"/>
</set> </class> </hibernate-mapping>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.kaishengit.pojo"> <class name="Student" table="student">
<id name="id">
<generator class="native"/>
</id> <property name="name"/>
<!-- name="teachers"指属性, -->
<set name="teachers" table="student_teacher">
<!-- student在这个关系表中的外键 -->
<key column="sid"/>
<many-to-many class="Teacher" column="tid"/>
</set> </class> </hibernate-mapping>
在hibernate.cfg.xml中添加这两项
程序执行
Teacher t1 = new Teacher();
t1.setTeachername("t1");
Teacher t2 = new Teacher();
t2.setTeachername("t2"); Student s1 = new Student();
s1.setStudentname("s1");
Student s2 = new Student();
s2.setStudentname("s2"); Set<Teacher> t= new HashSet<Teacher>();
t.add(t1);
t.add(t2);
s1.setTeachers(t);
s2.setTeachers(t); Set<Student> stu = new HashSet<Student>();
stu.add(s1);
stu.add(s2);
t1.setStudents(stu);
t2.setStudents(stu); session.save(s1);
session.save(s2);
session.save(t1);
session.save(t2);
两方都维护关系的时候,关系表中就会插入额外一倍的无用数据
这是错误的,所以多对多必须指明一方放弃维护 inverse="true"
<set name="students" table="student_teacher" inverse="true" >
<key column="tid"/>
<many-to-many class="Student" column="sid" order-by="id desc,name asc"/>
</set>