多对多配置
多对多实体关系也很常见 比如学生和课程的关系 一个学生可以选修多门课程 一个课程可以被多名学生选修
在关系数据库中对于多对多关联关系的处理一般采用中间表的形式 将多对多的关系转换成两个一对多的关系
图解:
实例代码:
创建student和course俩个表的实体类
编写映射文件
编写测试类
public class hibernateTest {
// 选课
@Test
public void test5() {
Session session = HibernateUtil.openSession();
Transaction tx = session.beginTransaction();
// 获取要退选的学生和课程
Student student = (Student) session.get(Student.class, 1);
Course course = (Course) session.get(Course.class, 2);
student.getCourses().add(course);
tx.commit();
session.close();
}
// 退选
@Test
public void test4() {
Session session = HibernateUtil.openSession();
Transaction tx = session.beginTransaction();
// 获取要退选的学生和课程
Student student = (Student) session.get(Student.class, 1);
Course course = (Course) session.get(Course.class, 2);
student.getCourses().remove(course);
tx.commit();
session.close();
}
// 级联删除
@Test
public void test3() {
Session session = HibernateUtil.openSession();
Transaction tx = session.beginTransaction();
Student student = (Student) session.get(Student.class, 2);
session.delete(student);
tx.commit();
session.close();
}
// 级联保存
@Test
public void test2() {
Session session = HibernateUtil.openSession();
Transaction tx = session.beginTransaction();
// 创建学生
Student student1 = new Student();
student1.setSname("赵云");
Student student2 = new Student();
student2.setSname("马超");
// 创建课程
Course course1 = new Course();
course1.setCname("java从入门到精通");
Course course2 = new Course();
course2.setCname("mysql从入门到精通");
// 赵云选择课程1和课程2
student1.getCourses().add(course1);
student1.getCourses().add(course2);
// course1.getStudents().add(student1);
// course2.getStudents().add(student1);
// 马超选择课程1
student2.getCourses().add(course1);
// course1.getStudents().add(student2);
session.save(student1);
session.save(student2);
tx.commit();
session.close();
}