多对多关联xml配置测试

前端之家收集整理的这篇文章主要介绍了多对多关联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。也不能都不设置,否则会报异常(

1Duplicate entry'2-2' for key 'PRIMARY'

2Could notsynchronize database state with session

2ConstrainViolationException: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,?)

原文链接:https://www.f2er.com/xml/295738.html

猜你在找的XML相关文章