1、Hibernate 关联关系映射(多对多)文章分类: Java 编程 双向多对多关联关系映射(many-to-many)在关系型数据库中对于多对多关联关系的处理一般采用中间表的形式,将多对多的关系转化成两个一对多的关系。以学生-老师作为实例对象设计:Class Teacherprivate long id;private String name;private Set students; Class Studentprivate long id;private String name;private Set teachers; 对象关系映射Teacher 对象映射文件Student 对象映射文
2、件简单测试Testpublic void many2manySave() Teacher t1 = new Teacher();t1.setName(“t1“);Teacher t2 = new Teacher();t2.setName(“t2“);Student s1 = new Student();s1.setName(“s1“);Student s2 = new Student();s2.setName(“s2“);/ 维护关系Set students = new HashSet();students.add(s1);students.add(s2);Set teachers = new
3、 HashSet();teachers.add(t1);teachers.add(t2);/ 多对多关系维护时,维护一边的关系即可,当双边关系被维护时,会出现中间表的重复数据,导致复合组建重复,而出现异常。t1.setStudents(students);t2.setStudents(students);Session session = HibernateUtil.getSession();session.beginTransaction();/ 保存对象session.save(s1);session.save(s2);session.save(t1);session.save(t2);session.getTransaction().commit();session.close();