`
hugang357
  • 浏览: 181059 次
  • 性别: Icon_minigender_2
  • 来自: 深圳
社区版块
存档分类
最新评论

多对多关联关系的使用

    博客分类:
  • ssh
阅读更多
    Student(学生)和Course(课程)的关系就是多对多的关系。在映射多对多关系时,需要另外使用一个连接表(例如,Student_Course)。Student_Course表包含2个字段:CourseId和StuId。此外,在它们的映射文件中使用<many-to-many>标记。
Student的映射文件Student.hbm.xml中加入以下描述信息:

<set  name="courses"  table=" Student_Course" lazy="false"
inverse="false" cascade="save-update" >
<key column="StuId"/>
<many-to-many class="test.Course" column="CourseId" />
</set>

相应地,Course的映射文件Course.hbm.xml加入以下描述信息:

<set  name="students"  table=" Student_Course" lazy="false"
inverse="true" cascade="save-update" >
<key column="CourseId"/>
<many-to-many class="test.Student" column="StuId"  />
</set>

1.添加关联关系

首先让我们编一个程序来看看一个名为Bill的学生选择了什么课程:

……
//获得包含Bill的Student对象
Student stu = (Student) session.createQuery(“from Student s where s.name =
‘Bill’ ”) .uniqueResult();

List ls = new ArrayList(stu.getCourses());
for(int i=0; i<ls.size(); i++) {
Course course = (Course)ls.get(i);  //获得Course对象
System.out.println(course.getName()); //打印Bill所选课程的清单
}
…..

现在Bill还想选修business课程,这对于程序员来说只是为Bill添加了一个到business的关联,也就是说在student_course表中新添一条记录,而T_Student 和T_Course表都不用变更。

……
Student stu = (Student) session.createQuery(“from Student s where
s.name = ‘Bill’ ”) .uniqueResult();
Course course = (Course) session.createQuery(“from Course c where c.name =
‘business’ ”) .uniqueResult();
//设置stu与course的相互关系
stu.getCourses().add(course);
course.getStudents().add(stu);
…..

2.删除关联关系

删除关联关系比较简单,直接调用对象集合的remove()方法删除不要的对象即可。例如,要从学生Bill的选修课清单中删除politics和chemistry两门课,程序如下:

…….
Student stu = (Student) session.createQuery("from Student s where
s.name = 'Bill' ") .uniqueResult();
Course course1 = (Course) session.createQuery("from Course c where c.name =
'politics' ") .uniqueResult();
Course course2 = (Course) session.createQuery("from Course c where c.name =
'chemistry' ") .uniqueResult();
stu.getCourse().remove(course1); //删除politics课程
stu.getCourse().remove(course2); //删除chemisty课程
…….

运行以上语句将从student_course表中删除这两条记录,但T_Student和T_Course表没有任何变化。
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics