说明:
关系操作
1.增加关系相当于在第三张表中插入一行数据
2.解除关系相当于在第三张表中删除一行数据
3.更新关系?
先删除后增加
4.谁维护关系,效率都一样,看页面的需求
1、多对多的结构是三张表
2、多对多是类与集合的关系
映射文件
在更新课程的时候,级联更新学生
@Test
public void testUpdateCourse_Cascade_Update_Student(){
Session session = sessionFactory.getCurrentSession();
Transaction transaction = session.beginTransaction();
Course course = (Course)session.get(Course.class, 1L);
//选修该课程的所有的学生
Set<Student> students = course.getStudents();
for (Student student : students) {
student.setName("asfd");
}
transaction.commit();
}
/**
* 解除课程1和所有的学生之间的关系
* delete
from
student_course
where
cid=?
把第三张表中针对cid为1的数据全部删除了
*/
@Test
public void testRealseAllR(){
Session session = sessionFactory.getCurrentSession();
Transaction transaction = session.beginTransaction();
Course course = (Course)session.get(Course.class, 1L);
course.setStudents(null);
transaction.commit();
}
/**
* 把学生1从课程1转到课程2
* Hibernate: 解除关系
delete
from
student_course
where
sid=?
and cid=?
Hibernate: 增加关系
insert
into
student_course
(sid, cid)
values
(?, ?)
*/
@Test
public void testStudentFromCourseToCourse(){
Session session = sessionFactory.getCurrentSession();
Transaction transaction = session.beginTransaction();
Student student = (Student)session.get(Student.class, 1L);
Course course1 = (Course)session.get(Course.class, 1L);
Course course2 = (Course)session.get(Course.class, 2L);
student.getCourses().remove(course1);//解除关系
student.getCourses().add(course2);//建立关系
transaction.commit();
}
/**
* 删除一个学生
* Hibernate:
delete 解除关系
from
student_course
where
sid=?
Hibernate:
delete 删除学生
from
Student
where
sid=?
*/
@Test
public void testDeleteStudent(){
Session session = sessionFactory.getCurrentSession();
Transaction transaction = session.beginTransaction();
Student student = (Student)session.get(Student.class, 1L);
session.delete(student);
transaction.commit();
}