您的位置:首页 > 其它

多对多关联xml配置测试

2015-12-20 19:16 621 查看
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, stu_id) values (?, ?)

Hibernate: insert into stu_course (course_id, stu_id) values (?, ?)

Hibernate: insert into stu_course (course_id, stu_id) values (?, ?)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: