多对多关联xml配置测试
Student<------>Course: 1.Student.hbm.xml: <hibernate-mapping package="com.buaa.hibernate.bean"> <class name="Student"> <id name="id" column="id"> <generator class="native"></generator> </id> <property name="sname" column="stu_name"></property> <set name="courses" table="stu_course" inverse="true"> <key column="stu_id"></key> <many-to-many class="Course" column="course_id"></many-to-many> </set> </class> </hibernate-mapping> 2.Course.hbm.xml: <hibernate-mapping package="com.buaa.hibernate.bean"> <class name="Course"> <id name="id" column="id"> <generator class="native"></generator> </id> <property name="cname" column="course_name"></property> <set name="students" table="stu_course"> <key column="course_id"></key> <many-to-many class="Student" column="stu_id"></many-to-many> </set> </class> </hibernate-mapping> ☆☆☆ 注意:inverse属性:只能有一个设置为true。也不能都不设置,否则会报异常( 1、Duplicate entry'2-2' for key 'PRIMARY'; 2、Could notsynchronize database state with session; 2、ConstrainViolationException:Could not execute JDBC batch update;)
3.Test测试类: public class Test extends TestCase { public void testMTM(){ //MySessionFactory是自己写的一个类,获取session Session session = MySessionFactory.getSession(0); Student stu = new Student(); stu.setSname("jack"); Student stu2 = new Student(); stu2.setSname("simon"); Course course = new Course(); course.setCname("English"); Course course2 = new Course(); course2.setCname("Math"); Set<Course> courses = new HashSet<Course>(); courses.add(course); courses.add(course2); Set<Student> students = new HashSet<Student>(); students.add(stu); students.add(stu2); stu.setCourses(courses); stu2.setCourses(courses); course.setStudents(students); course2.setStudents(students); session.save(course); session.save(course2); session.save(stu); session.save(stu2); session.beginTransaction().commit(); session.close(); } } 4.控制台输出: Hibernate: insert into Course (course_name) values (?) Hibernate: insert into Course (course_name) values (?) Hibernate: insert into Student (stu_name) values (?) Hibernate: insert into Student (stu_name) values (?) Hibernate: insert into stu_course (course_id,stu_id) values (?,?) Hibernate: insert into stu_course (course_id,?) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |