有两张表, 一张班级表(T_class),一张学生表(T_student).
学生类:省略get/set方法
Java code
public class Student {
private Integer studentId;
private String studentName;
private Classes classes;
}
班级类:省略get/set方法
Java code
public class Classes{
private Integer classId;
private String className;
private Set<Student> students = new HashSet<Student>();
}
Student.hbm.xml
XML code
<hibernate-mapping package="wxm.beans">
<class name="Student" table="student">
<id name="studentId" type="integer" column="student_id">
<generator class="identity" />
</id>
<property name="studentName" length="20" not-null="true"
column="student_name" />
<property name="perform" />
<many-to-one name="classes" column="class_id"
outer-join="true" class="wxm.beans.Classes" />
</class>
</hibernate-mapping>
Classes.hbm.xml
XML code
<hibernate-mapping package="wxm.beans">
<class name="Classes" table="t_class">
<id name="classId" type="integer" column="class_id">
<generator class="identity" />
</id>
<property name="className" length="20" not-null="true"
column="class_name" />
<set name="students" outer-join="true" inverse="true">
<key column="class_id" />
<one-to-many class="wxm.beans.Student" />
</set>
</class>
</hibernate-mapping>
学生和班级是多对一关系,班级和学生是一对多关系,是否两个XML都要写上他们的关系呢?
另外一个问题是关于cascade的
@Test
public void save() {
Classes claz = new Classes("英语班");
classService.addClass(claz);
Student student = new Student("王小二");
student.setClasses(classService.getClass(1));
student.setPerform(55.5f);
studentService.addStudent(student);
}
cascade=ALL的时候上面这段代码是不成功的。还麻烦大神解释下。
另外删除cascade成功保存之后,要删除班级而不得。
@Test
public void delClass() {
classService.getClass(1).getStudents().remove(
studentService.getStudent(1));
classService.delClass(1);
}